blob: cd553f0811a72323d6544e72f6fa34c854421889 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000058#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000059#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000062#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000063#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000064#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000066#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000067#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000068#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000069using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000070using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000077
Chris Lattnerb109b5c2009-12-21 06:03:05 +000078/// SelectPatternFlavor - We can match a variety of different patterns for
79/// select operations.
80enum SelectPatternFlavor {
81 SPF_UNKNOWN = 0,
82 SPF_SMIN, SPF_UMIN,
83 SPF_SMAX, SPF_UMAX
84 //SPF_ABS - TODO.
85};
86
Chris Lattner0e5f4992006-12-19 21:40:18 +000087namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000088 /// InstCombineWorklist - This is the worklist management logic for
89 /// InstCombine.
90 class InstCombineWorklist {
91 SmallVector<Instruction*, 256> Worklist;
92 DenseMap<Instruction*, unsigned> WorklistMap;
93
94 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
95 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
96 public:
97 InstCombineWorklist() {}
98
99 bool isEmpty() const { return Worklist.empty(); }
100
101 /// Add - Add the specified instruction to the worklist if it isn't already
102 /// in it.
103 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +0000104 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
105 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +0000106 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +0000107 }
Chris Lattner873ff012009-08-30 05:55:36 +0000108 }
109
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000110 void AddValue(Value *V) {
111 if (Instruction *I = dyn_cast<Instruction>(V))
112 Add(I);
113 }
114
Chris Lattner67f7d542009-10-12 03:58:40 +0000115 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
116 /// which should only be done when the worklist is empty and when the group
117 /// has no duplicates.
118 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
119 assert(Worklist.empty() && "Worklist must be empty to add initial group");
120 Worklist.reserve(NumEntries+16);
121 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
122 for (; NumEntries; --NumEntries) {
123 Instruction *I = List[NumEntries-1];
124 WorklistMap.insert(std::make_pair(I, Worklist.size()));
125 Worklist.push_back(I);
126 }
127 }
128
Chris Lattner7a1e9242009-08-30 06:13:40 +0000129 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000130 void Remove(Instruction *I) {
131 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
132 if (It == WorklistMap.end()) return; // Not in worklist.
133
134 // Don't bother moving everything down, just null out the slot.
135 Worklist[It->second] = 0;
136
137 WorklistMap.erase(It);
138 }
139
140 Instruction *RemoveOne() {
141 Instruction *I = Worklist.back();
142 Worklist.pop_back();
143 WorklistMap.erase(I);
144 return I;
145 }
146
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000147 /// AddUsersToWorkList - When an instruction is simplified, add all users of
148 /// the instruction to the work lists because they might get more simplified
149 /// now.
150 ///
151 void AddUsersToWorkList(Instruction &I) {
152 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
153 UI != UE; ++UI)
154 Add(cast<Instruction>(*UI));
155 }
156
Chris Lattner873ff012009-08-30 05:55:36 +0000157
158 /// Zap - check that the worklist is empty and nuke the backing store for
159 /// the map if it is large.
160 void Zap() {
161 assert(WorklistMap.empty() && "Worklist empty, but map not?");
162
163 // Do an explicit clear, this shrinks the map if needed.
164 WorklistMap.clear();
165 }
166 };
167} // end anonymous namespace.
168
169
170namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000171 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
172 /// just like the normal insertion helper, but also adds any new instructions
173 /// to the instcombine worklist.
174 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
175 InstCombineWorklist &Worklist;
176 public:
177 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
178
179 void InsertHelper(Instruction *I, const Twine &Name,
180 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
181 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
182 Worklist.Add(I);
183 }
184 };
185} // end anonymous namespace
186
187
188namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000189 class InstCombiner : public FunctionPass,
190 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000191 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000192 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000193 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000194 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000195 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000196 InstCombineWorklist Worklist;
197
Chris Lattner74381062009-08-30 07:44:24 +0000198 /// Builder - This is an IRBuilder that automatically inserts new
199 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000200 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000201 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000202
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000203 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000204 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000205
Owen Andersone922c022009-07-22 00:24:57 +0000206 LLVMContext *Context;
207 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000208
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000209 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000210 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000211
212 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000213
Chris Lattner97e52e42002-04-28 21:27:06 +0000214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000215 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000216 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000217 }
218
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000219 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000220
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000221 // Visitation implementation - Implement instruction combining for different
222 // instruction types. The semantics are as follows:
223 // Return Value:
224 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000225 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000226 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000227 //
Chris Lattner7e708292002-06-25 16:13:24 +0000228 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000229 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000230 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000231 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000232 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000234 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000235 Instruction *visitURem(BinaryOperator &I);
236 Instruction *visitSRem(BinaryOperator &I);
237 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000238 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000239 Instruction *commonRemTransforms(BinaryOperator &I);
240 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000241 Instruction *commonDivTransforms(BinaryOperator &I);
242 Instruction *commonIDivTransforms(BinaryOperator &I);
243 Instruction *visitUDiv(BinaryOperator &I);
244 Instruction *visitSDiv(BinaryOperator &I);
245 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000246 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000247 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000248 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000249 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000250 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000251 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000252 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000253 Instruction *visitOr (BinaryOperator &I);
254 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000255 Instruction *visitShl(BinaryOperator &I);
256 Instruction *visitAShr(BinaryOperator &I);
257 Instruction *visitLShr(BinaryOperator &I);
258 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000259 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
260 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000261 Instruction *visitFCmpInst(FCmpInst &I);
262 Instruction *visitICmpInst(ICmpInst &I);
263 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000264 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
265 Instruction *LHS,
266 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000267 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
268 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000269 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000270 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000271 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000272 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000273 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000274 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000275 Instruction *commonCastTransforms(CastInst &CI);
276 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000277 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000278 Instruction *visitTrunc(TruncInst &CI);
279 Instruction *visitZExt(ZExtInst &CI);
280 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000281 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000282 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000283 Instruction *visitFPToUI(FPToUIInst &FI);
284 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000285 Instruction *visitUIToFP(CastInst &CI);
286 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000287 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000288 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000289 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000290 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
291 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000292 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000293 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
294 Value *A, Value *B, Instruction &Outer,
295 SelectPatternFlavor SPF2, Value *C);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000296 Instruction *visitSelectInst(SelectInst &SI);
297 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000298 Instruction *visitCallInst(CallInst &CI);
299 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000300
301 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000302 Instruction *visitPHINode(PHINode &PN);
303 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000304 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000305 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000306 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000307 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000308 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000309 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000310 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000311 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000312 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000313 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000314
315 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000316 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000317
Chris Lattner9fe38862003-06-19 17:00:31 +0000318 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000319 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000320 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000321 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000322 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
323 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000324 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000325 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
326
Chris Lattner9fe38862003-06-19 17:00:31 +0000327
Chris Lattner28977af2004-04-05 01:30:19 +0000328 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000329 // InsertNewInstBefore - insert an instruction New before instruction Old
330 // in the program. Add the new instruction to the worklist.
331 //
Chris Lattner955f3312004-09-28 21:48:02 +0000332 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000333 assert(New && New->getParent() == 0 &&
334 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000335 BasicBlock *BB = Old.getParent();
336 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000337 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000338 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000339 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000340
Chris Lattner8b170942002-08-09 23:47:40 +0000341 // ReplaceInstUsesWith - This method is to be used when an instruction is
342 // found to be dead, replacable with another preexisting expression. Here
343 // we add all uses of I to the worklist, replace all uses of I with the new
344 // value, then return I, so that the inst combiner will know that I was
345 // modified.
346 //
347 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000348 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000349
350 // If we are replacing the instruction with itself, this must be in a
351 // segment of unreachable code, so just clobber the instruction.
352 if (&I == V)
353 V = UndefValue::get(I.getType());
354
355 I.replaceAllUsesWith(V);
356 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000357 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000358
359 // EraseInstFromFunction - When dealing with an instruction that has side
360 // effects or produces a void value, we can't rely on DCE to delete the
361 // instruction. Instead, visit methods should return the value returned by
362 // this function.
363 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000364 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000365
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000366 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000367 // Make sure that we reprocess all operands now that we reduced their
368 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000369 if (I.getNumOperands() < 8) {
370 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
371 if (Instruction *Op = dyn_cast<Instruction>(*i))
372 Worklist.Add(Op);
373 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000374 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000375 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000376 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000377 return 0; // Don't do anything with FI
378 }
Chris Lattner173234a2008-06-02 01:18:21 +0000379
380 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
381 APInt &KnownOne, unsigned Depth = 0) const {
382 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
383 }
384
385 bool MaskedValueIsZero(Value *V, const APInt &Mask,
386 unsigned Depth = 0) const {
387 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
388 }
389 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
390 return llvm::ComputeNumSignBits(Op, TD, Depth);
391 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000392
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000393 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000394
Reid Spencere4d87aa2006-12-23 06:05:41 +0000395 /// SimplifyCommutative - This performs a few simplifications for
396 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000397 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000398
Chris Lattner886ab6c2009-01-31 08:15:18 +0000399 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
400 /// based on the demanded bits.
401 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
402 APInt& KnownZero, APInt& KnownOne,
403 unsigned Depth);
404 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000405 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000406 unsigned Depth=0);
407
408 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
409 /// SimplifyDemandedBits knows about. See if the instruction has any
410 /// properties that allow us to simplify its operands.
411 bool SimplifyDemandedInstructionBits(Instruction &Inst);
412
Evan Cheng388df622009-02-03 10:05:09 +0000413 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
414 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000415
Chris Lattner5d1704d2009-09-27 19:57:57 +0000416 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
417 // which has a PHI node as operand #0, see if we can fold the instruction
418 // into the PHI (which is only possible if all operands to the PHI are
419 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000420 //
421 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
422 // that would normally be unprofitable because they strongly encourage jump
423 // threading.
424 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000425
Chris Lattnerbac32862004-11-14 19:13:23 +0000426 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
427 // operator and they all are only used by the PHI, PHI together their
428 // inputs, and do the operation once, to the result of the PHI.
429 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000430 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000431 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000432 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000433
Chris Lattner7da52b22006-11-01 04:51:18 +0000434
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000435 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
436 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000437
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000438 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000439 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000440 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000441 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000442 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000443 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000444 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000445 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000446 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000447
Chris Lattnerafe91a52006-06-15 19:07:26 +0000448
Reid Spencerc55b2432006-12-13 18:21:21 +0000449 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000450
Dan Gohman6de29f82009-06-15 22:12:54 +0000451 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000452 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000453 unsigned GetOrEnforceKnownAlignment(Value *V,
454 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000455
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000456 };
Chris Lattner873ff012009-08-30 05:55:36 +0000457} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000458
Dan Gohman844731a2008-05-13 00:00:25 +0000459char InstCombiner::ID = 0;
460static RegisterPass<InstCombiner>
461X("instcombine", "Combine redundant instructions");
462
Chris Lattner4f98c562003-03-10 21:43:22 +0000463// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000464// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000465static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000466 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000467 if (BinaryOperator::isNeg(V) ||
468 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000469 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000470 return 3;
471 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000472 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000473 if (isa<Argument>(V)) return 3;
474 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000475}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000476
Chris Lattnerc8802d22003-03-11 00:12:48 +0000477// isOnlyUse - Return true if this instruction will be deleted if we stop using
478// it.
479static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000480 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000481}
482
Chris Lattner4cb170c2004-02-23 06:38:22 +0000483// getPromotedType - Return the specified type promoted as it would be to pass
484// though a va_arg area...
485static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000486 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
487 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000488 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000489 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000490 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000491}
492
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000493/// ShouldChangeType - Return true if it is desirable to convert a computation
494/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
495/// type for example, or from a smaller to a larger illegal type.
496static bool ShouldChangeType(const Type *From, const Type *To,
497 const TargetData *TD) {
498 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
499
500 // If we don't have TD, we don't know if the source/dest are legal.
501 if (!TD) return false;
502
503 unsigned FromWidth = From->getPrimitiveSizeInBits();
504 unsigned ToWidth = To->getPrimitiveSizeInBits();
505 bool FromLegal = TD->isLegalInteger(FromWidth);
506 bool ToLegal = TD->isLegalInteger(ToWidth);
507
508 // If this is a legal integer from type, and the result would be an illegal
509 // type, don't do the transformation.
510 if (FromLegal && !ToLegal)
511 return false;
512
513 // Otherwise, if both are illegal, do not increase the size of the result. We
514 // do allow things like i160 -> i64, but not i64 -> i160.
515 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
516 return false;
517
518 return true;
519}
520
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000521/// getBitCastOperand - If the specified operand is a CastInst, a constant
522/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
523/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000524static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000525 if (Operator *O = dyn_cast<Operator>(V)) {
526 if (O->getOpcode() == Instruction::BitCast)
527 return O->getOperand(0);
528 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
529 if (GEP->hasAllZeroIndices())
530 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000531 }
Chris Lattnereed48272005-09-13 00:40:14 +0000532 return 0;
533}
534
Reid Spencer3da59db2006-11-27 01:05:10 +0000535/// This function is a wrapper around CastInst::isEliminableCastPair. It
536/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000537static Instruction::CastOps
538isEliminableCastPair(
539 const CastInst *CI, ///< The first cast instruction
540 unsigned opcode, ///< The opcode of the second cast instruction
541 const Type *DstTy, ///< The target type for the second cast instruction
542 TargetData *TD ///< The target data for pointer size
543) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000544
Reid Spencer3da59db2006-11-27 01:05:10 +0000545 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
546 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000547
Reid Spencer3da59db2006-11-27 01:05:10 +0000548 // Get the opcodes of the two Cast instructions
549 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
550 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000551
Chris Lattnera0e69692009-03-24 18:35:40 +0000552 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000553 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000554 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000555
556 // We don't want to form an inttoptr or ptrtoint that converts to an integer
557 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000558 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000559 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000561 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000562 Res = 0;
563
564 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000565}
566
567/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
568/// in any code being generated. It does not require codegen if V is simple
569/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000570static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
571 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000572 if (V->getType() == Ty || isa<Constant>(V)) return false;
573
Chris Lattner01575b72006-05-25 23:24:33 +0000574 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000575 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000576 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000577 return false;
578 return true;
579}
580
Chris Lattner4f98c562003-03-10 21:43:22 +0000581// SimplifyCommutative - This performs a few simplifications for commutative
582// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000583//
Chris Lattner4f98c562003-03-10 21:43:22 +0000584// 1. Order operands such that they are listed from right (least complex) to
585// left (most complex). This puts constants before unary operators before
586// binary operators.
587//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000588// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
589// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000590//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000592 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000593 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000594 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000595
Chris Lattner4f98c562003-03-10 21:43:22 +0000596 if (!I.isAssociative()) return Changed;
597 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000598 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
599 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
600 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000601 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000602 cast<Constant>(I.getOperand(1)),
603 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000604 I.setOperand(0, Op->getOperand(0));
605 I.setOperand(1, Folded);
606 return true;
607 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
608 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
609 isOnlyUse(Op) && isOnlyUse(Op1)) {
610 Constant *C1 = cast<Constant>(Op->getOperand(1));
611 Constant *C2 = cast<Constant>(Op1->getOperand(1));
612
613 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000614 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000615 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616 Op1->getOperand(0),
617 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000618 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000619 I.setOperand(0, New);
620 I.setOperand(1, Folded);
621 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000622 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000623 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000624 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000625}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000626
Chris Lattner8d969642003-03-10 23:06:50 +0000627// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
628// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000629//
Dan Gohman186a6362009-08-12 16:04:34 +0000630static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000631 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000632 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000633
Chris Lattner0ce85802004-12-14 20:08:06 +0000634 // Constants can be considered to be negated values if they can be folded.
635 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000636 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000637
638 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
639 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000640 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000641
Chris Lattner8d969642003-03-10 23:06:50 +0000642 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000643}
644
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000645// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
646// instruction if the LHS is a constant negative zero (which is the 'negate'
647// form).
648//
Dan Gohman186a6362009-08-12 16:04:34 +0000649static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000650 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000651 return BinaryOperator::getFNegArgument(V);
652
653 // Constants can be considered to be negated values if they can be folded.
654 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000655 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000656
657 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
658 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000659 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000660
661 return 0;
662}
663
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000664/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
665/// returning the kind and providing the out parameter results if we
666/// successfully match.
667static SelectPatternFlavor
668MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
669 SelectInst *SI = dyn_cast<SelectInst>(V);
670 if (SI == 0) return SPF_UNKNOWN;
671
672 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
673 if (ICI == 0) return SPF_UNKNOWN;
674
675 LHS = ICI->getOperand(0);
676 RHS = ICI->getOperand(1);
677
678 // (icmp X, Y) ? X : Y
679 if (SI->getTrueValue() == ICI->getOperand(0) &&
680 SI->getFalseValue() == ICI->getOperand(1)) {
681 switch (ICI->getPredicate()) {
682 default: return SPF_UNKNOWN; // Equality.
683 case ICmpInst::ICMP_UGT:
684 case ICmpInst::ICMP_UGE: return SPF_UMAX;
685 case ICmpInst::ICMP_SGT:
686 case ICmpInst::ICMP_SGE: return SPF_SMAX;
687 case ICmpInst::ICMP_ULT:
688 case ICmpInst::ICMP_ULE: return SPF_UMIN;
689 case ICmpInst::ICMP_SLT:
690 case ICmpInst::ICMP_SLE: return SPF_SMIN;
691 }
692 }
693
694 // (icmp X, Y) ? Y : X
695 if (SI->getTrueValue() == ICI->getOperand(1) &&
696 SI->getFalseValue() == ICI->getOperand(0)) {
697 switch (ICI->getPredicate()) {
698 default: return SPF_UNKNOWN; // Equality.
699 case ICmpInst::ICMP_UGT:
700 case ICmpInst::ICMP_UGE: return SPF_UMIN;
701 case ICmpInst::ICMP_SGT:
702 case ICmpInst::ICMP_SGE: return SPF_SMIN;
703 case ICmpInst::ICMP_ULT:
704 case ICmpInst::ICMP_ULE: return SPF_UMAX;
705 case ICmpInst::ICMP_SLT:
706 case ICmpInst::ICMP_SLE: return SPF_SMAX;
707 }
708 }
709
710 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
711
712 return SPF_UNKNOWN;
713}
714
Chris Lattner48b59ec2009-10-26 15:40:07 +0000715/// isFreeToInvert - Return true if the specified value is free to invert (apply
716/// ~ to). This happens in cases where the ~ can be eliminated.
717static inline bool isFreeToInvert(Value *V) {
718 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000719 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000720 return true;
721
722 // Constants can be considered to be not'ed values.
723 if (isa<ConstantInt>(V))
724 return true;
725
726 // Compares can be inverted if they have a single use.
727 if (CmpInst *CI = dyn_cast<CmpInst>(V))
728 return CI->hasOneUse();
729
730 return false;
731}
732
733static inline Value *dyn_castNotVal(Value *V) {
734 // If this is not(not(x)) don't return that this is a not: we want the two
735 // not's to be folded first.
736 if (BinaryOperator::isNot(V)) {
737 Value *Operand = BinaryOperator::getNotArgument(V);
738 if (!isFreeToInvert(Operand))
739 return Operand;
740 }
Chris Lattner8d969642003-03-10 23:06:50 +0000741
742 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000743 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000744 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000745 return 0;
746}
747
Chris Lattner48b59ec2009-10-26 15:40:07 +0000748
749
Chris Lattnerc8802d22003-03-11 00:12:48 +0000750// dyn_castFoldableMul - If this value is a multiply that can be folded into
751// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000752// non-constant operand of the multiply, and set CST to point to the multiplier.
753// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000754//
Dan Gohman186a6362009-08-12 16:04:34 +0000755static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000756 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000757 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000758 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000759 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000760 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000761 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000762 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000763 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000764 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000765 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000766 CST = ConstantInt::get(V->getType()->getContext(),
767 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000768 return I->getOperand(0);
769 }
770 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000771 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000772}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000773
Reid Spencer7177c3a2007-03-25 05:33:51 +0000774/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000775static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000776 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000777 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000778}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000779/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000780static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000781 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000782 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000783}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000784/// MultiplyOverflows - True if the multiply can not be expressed in an int
785/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000786static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000787 uint32_t W = C1->getBitWidth();
788 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
789 if (sign) {
790 LHSExt.sext(W * 2);
791 RHSExt.sext(W * 2);
792 } else {
793 LHSExt.zext(W * 2);
794 RHSExt.zext(W * 2);
795 }
796
797 APInt MulExt = LHSExt * RHSExt;
798
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000799 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000800 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000801
802 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
803 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
804 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000805}
Chris Lattner955f3312004-09-28 21:48:02 +0000806
Reid Spencere7816b52007-03-08 01:52:58 +0000807
Chris Lattner255d8912006-02-11 09:31:47 +0000808/// ShrinkDemandedConstant - Check to see if the specified operand of the
809/// specified instruction is a constant integer. If so, check to see if there
810/// are any bits set in the constant that are not demanded. If so, shrink the
811/// constant and return true.
812static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000813 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000814 assert(I && "No instruction?");
815 assert(OpNo < I->getNumOperands() && "Operand index too large");
816
817 // If the operand is not a constant integer, nothing to do.
818 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
819 if (!OpC) return false;
820
821 // If there are no bits set that aren't demanded, nothing to do.
822 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
823 if ((~Demanded & OpC->getValue()) == 0)
824 return false;
825
826 // This instruction is producing bits that are not demanded. Shrink the RHS.
827 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000828 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000829 return true;
830}
831
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000832// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
833// set of known zero and one bits, compute the maximum and minimum values that
834// could have the specified known zero and known one bits, returning them in
835// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000836static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000837 const APInt& KnownOne,
838 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000839 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
840 KnownZero.getBitWidth() == Min.getBitWidth() &&
841 KnownZero.getBitWidth() == Max.getBitWidth() &&
842 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000843 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000844
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000845 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
846 // bit if it is unknown.
847 Min = KnownOne;
848 Max = KnownOne|UnknownBits;
849
Dan Gohman1c8491e2009-04-25 17:12:48 +0000850 if (UnknownBits.isNegative()) { // Sign bit is unknown
851 Min.set(Min.getBitWidth()-1);
852 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000853 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000854}
855
856// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
857// a set of known zero and one bits, compute the maximum and minimum values that
858// could have the specified known zero and known one bits, returning them in
859// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000860static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000861 const APInt &KnownOne,
862 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000863 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
864 KnownZero.getBitWidth() == Min.getBitWidth() &&
865 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000866 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000867 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000868
869 // The minimum value is when the unknown bits are all zeros.
870 Min = KnownOne;
871 // The maximum value is when the unknown bits are all ones.
872 Max = KnownOne|UnknownBits;
873}
Chris Lattner255d8912006-02-11 09:31:47 +0000874
Chris Lattner886ab6c2009-01-31 08:15:18 +0000875/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
876/// SimplifyDemandedBits knows about. See if the instruction has any
877/// properties that allow us to simplify its operands.
878bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000879 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000880 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
881 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
882
883 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
884 KnownZero, KnownOne, 0);
885 if (V == 0) return false;
886 if (V == &Inst) return true;
887 ReplaceInstUsesWith(Inst, V);
888 return true;
889}
890
891/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
892/// specified instruction operand if possible, updating it in place. It returns
893/// true if it made any change and false otherwise.
894bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
895 APInt &KnownZero, APInt &KnownOne,
896 unsigned Depth) {
897 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
898 KnownZero, KnownOne, Depth);
899 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000900 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000901 return true;
902}
903
904
905/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
906/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000907/// that only the bits set in DemandedMask of the result of V are ever used
908/// downstream. Consequently, depending on the mask and V, it may be possible
909/// to replace V with a constant or one of its operands. In such cases, this
910/// function does the replacement and returns true. In all other cases, it
911/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000913/// to be zero in the expression. These are provided to potentially allow the
914/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
915/// the expression. KnownOne and KnownZero always follow the invariant that
916/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
917/// the bits in KnownOne and KnownZero may only be accurate for those bits set
918/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
919/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920///
921/// This returns null if it did not change anything and it permits no
922/// simplification. This returns V itself if it did some simplification of V's
923/// operands based on the information about what bits are demanded. This returns
924/// some other non-null value if it found out that V is equal to another value
925/// in the context where the specified bits are demanded, but not for all users.
926Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
927 APInt &KnownZero, APInt &KnownOne,
928 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000929 assert(V != 0 && "Null pointer of Value???");
930 assert(Depth <= 6 && "Limit Search Depth");
931 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000932 const Type *VTy = V->getType();
933 assert((TD || !isa<PointerType>(VTy)) &&
934 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000935 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
936 (!VTy->isIntOrIntVector() ||
937 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000938 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000939 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000940 "Value *V, DemandedMask, KnownZero and KnownOne "
941 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
943 // We know all of the bits for a constant!
944 KnownOne = CI->getValue() & DemandedMask;
945 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000946 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000947 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000948 if (isa<ConstantPointerNull>(V)) {
949 // We know all of the bits for a constant!
950 KnownOne.clear();
951 KnownZero = DemandedMask;
952 return 0;
953 }
954
Chris Lattner08d2cc72009-01-31 07:26:06 +0000955 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000956 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 if (DemandedMask == 0) { // Not demanding any bits from V.
958 if (isa<UndefValue>(V))
959 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000960 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000961 }
962
Chris Lattner4598c942009-01-31 08:24:16 +0000963 if (Depth == 6) // Limit search depth.
964 return 0;
965
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000966 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
967 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
968
Dan Gohman1c8491e2009-04-25 17:12:48 +0000969 Instruction *I = dyn_cast<Instruction>(V);
970 if (!I) {
971 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
972 return 0; // Only analyze instructions.
973 }
974
Chris Lattner4598c942009-01-31 08:24:16 +0000975 // If there are multiple uses of this value and we aren't at the root, then
976 // we can't do any simplifications of the operands, because DemandedMask
977 // only reflects the bits demanded by *one* of the users.
978 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000979 // Despite the fact that we can't simplify this instruction in all User's
980 // context, we can at least compute the knownzero/knownone bits, and we can
981 // do simplifications that apply to *just* the one user if we know that
982 // this instruction has a simpler value in that context.
983 if (I->getOpcode() == Instruction::And) {
984 // If either the LHS or the RHS are Zero, the result is zero.
985 ComputeMaskedBits(I->getOperand(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1);
987 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
988 LHSKnownZero, LHSKnownOne, Depth+1);
989
990 // If all of the demanded bits are known 1 on one side, return the other.
991 // These bits cannot contribute to the result of the 'and' in this
992 // context.
993 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
994 (DemandedMask & ~LHSKnownZero))
995 return I->getOperand(0);
996 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
997 (DemandedMask & ~RHSKnownZero))
998 return I->getOperand(1);
999
1000 // If all of the demanded bits in the inputs are known zeros, return zero.
1001 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001002 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +00001003
1004 } else if (I->getOpcode() == Instruction::Or) {
1005 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1006 // only bits from X or Y are demanded.
1007
1008 // If either the LHS or the RHS are One, the result is One.
1009 ComputeMaskedBits(I->getOperand(1), DemandedMask,
1010 RHSKnownZero, RHSKnownOne, Depth+1);
1011 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1012 LHSKnownZero, LHSKnownOne, Depth+1);
1013
1014 // If all of the demanded bits are known zero on one side, return the
1015 // other. These bits cannot contribute to the result of the 'or' in this
1016 // context.
1017 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1018 (DemandedMask & ~LHSKnownOne))
1019 return I->getOperand(0);
1020 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1021 (DemandedMask & ~RHSKnownOne))
1022 return I->getOperand(1);
1023
1024 // If all of the potentially set bits on one side are known to be set on
1025 // the other side, just use the 'other' side.
1026 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1027 (DemandedMask & (~RHSKnownZero)))
1028 return I->getOperand(0);
1029 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1030 (DemandedMask & (~LHSKnownZero)))
1031 return I->getOperand(1);
1032 }
1033
Chris Lattner4598c942009-01-31 08:24:16 +00001034 // Compute the KnownZero/KnownOne bits to simplify things downstream.
1035 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1036 return 0;
1037 }
1038
1039 // If this is the root being simplified, allow it to have multiple uses,
1040 // just set the DemandedMask to all bits so that we can try to simplify the
1041 // operands. This allows visitTruncInst (for example) to simplify the
1042 // operand of a trunc without duplicating all the logic below.
1043 if (Depth == 0 && !V->hasOneUse())
1044 DemandedMask = APInt::getAllOnesValue(BitWidth);
1045
Reid Spencer8cb68342007-03-12 17:25:59 +00001046 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001047 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001048 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +00001049 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001050 case Instruction::And:
1051 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001052 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1053 RHSKnownZero, RHSKnownOne, Depth+1) ||
1054 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +00001055 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
1057 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1058 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001059
1060 // If all of the demanded bits are known 1 on one side, return the other.
1061 // These bits cannot contribute to the result of the 'and'.
1062 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1063 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001065 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1066 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 // If all of the demanded bits in the inputs are known zeros, return zero.
1070 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001071 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001072
1073 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001074 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001076
1077 // Output known-1 bits are only known if set in both the LHS & RHS.
1078 RHSKnownOne &= LHSKnownOne;
1079 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1080 RHSKnownZero |= LHSKnownZero;
1081 break;
1082 case Instruction::Or:
1083 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1085 RHSKnownZero, RHSKnownOne, Depth+1) ||
1086 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 return I;
1089 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1090 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001091
1092 // If all of the demanded bits are known zero on one side, return the other.
1093 // These bits cannot contribute to the result of the 'or'.
1094 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1095 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001096 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1098 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001100
1101 // If all of the potentially set bits on one side are known to be set on
1102 // the other side, just use the 'other' side.
1103 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1104 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001106 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1107 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001109
1110 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001111 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001113
1114 // Output known-0 bits are only known if clear in both the LHS & RHS.
1115 RHSKnownZero &= LHSKnownZero;
1116 // Output known-1 are known to be set if set in either the LHS | RHS.
1117 RHSKnownOne |= LHSKnownOne;
1118 break;
1119 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1121 RHSKnownZero, RHSKnownOne, Depth+1) ||
1122 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 return I;
1125 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1126 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001127
1128 // If all of the demanded bits are known zero on one side, return the other.
1129 // These bits cannot contribute to the result of the 'xor'.
1130 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
1135 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1136 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1137 (RHSKnownOne & LHSKnownOne);
1138 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1139 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1140 (RHSKnownOne & LHSKnownZero);
1141
1142 // If all of the demanded bits are known to be zero on one side or the
1143 // other, turn this into an *inclusive* or.
1144 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001145 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1146 Instruction *Or =
1147 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1148 I->getName());
1149 return InsertNewInstBefore(Or, *I);
1150 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001151
1152 // If all of the demanded bits on one side are known, and all of the set
1153 // bits on that side are also known to be set on the other side, turn this
1154 // into an AND, as we know the bits will be cleared.
1155 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1156 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1157 // all known
1158 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001159 Constant *AndC = Constant::getIntegerValue(VTy,
1160 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001162 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 }
1165 }
1166
1167 // If the RHS is a constant, see if we can simplify it.
1168 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001169 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
Chris Lattnerd0883142009-10-11 22:22:13 +00001172 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1173 // are flipping are known to be set, then the xor is just resetting those
1174 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1175 // simplifying both of them.
1176 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1177 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1178 isa<ConstantInt>(I->getOperand(1)) &&
1179 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1180 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1181 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1182 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1183 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1184
1185 Constant *AndC =
1186 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1187 Instruction *NewAnd =
1188 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1189 InsertNewInstBefore(NewAnd, *I);
1190
1191 Constant *XorC =
1192 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1193 Instruction *NewXor =
1194 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1195 return InsertNewInstBefore(NewXor, *I);
1196 }
1197
1198
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 RHSKnownZero = KnownZeroOut;
1200 RHSKnownOne = KnownOneOut;
1201 break;
1202 }
1203 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001204 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1205 RHSKnownZero, RHSKnownOne, Depth+1) ||
1206 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001207 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001208 return I;
1209 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1210 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001211
1212 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001213 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1214 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001216
1217 // Only known if known in both the LHS and RHS.
1218 RHSKnownOne &= LHSKnownOne;
1219 RHSKnownZero &= LHSKnownZero;
1220 break;
1221 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001222 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001223 DemandedMask.zext(truncBf);
1224 RHSKnownZero.zext(truncBf);
1225 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001227 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 DemandedMask.trunc(BitWidth);
1230 RHSKnownZero.trunc(BitWidth);
1231 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001232 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 break;
1234 }
1235 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001236 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001237 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001238
1239 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1240 if (const VectorType *SrcVTy =
1241 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1242 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1243 // Don't touch a bitcast between vectors of different element counts.
1244 return false;
1245 } else
1246 // Don't touch a scalar-to-vector bitcast.
1247 return false;
1248 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1249 // Don't touch a vector-to-scalar bitcast.
1250 return false;
1251
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 return I;
1255 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 break;
1257 case Instruction::ZExt: {
1258 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001259 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001260
Zhou Shengd48653a2007-03-29 04:45:55 +00001261 DemandedMask.trunc(SrcBitWidth);
1262 RHSKnownZero.trunc(SrcBitWidth);
1263 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001265 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 DemandedMask.zext(BitWidth);
1268 RHSKnownZero.zext(BitWidth);
1269 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001272 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 break;
1274 }
1275 case Instruction::SExt: {
1276 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001277 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001278
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001280 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001281
Zhou Sheng01542f32007-03-29 02:26:30 +00001282 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001283 // If any of the sign extended bits are demanded, we know that the sign
1284 // bit is demanded.
1285 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001286 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287
Zhou Shengd48653a2007-03-29 04:45:55 +00001288 InputDemandedBits.trunc(SrcBitWidth);
1289 RHSKnownZero.trunc(SrcBitWidth);
1290 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001292 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001293 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 InputDemandedBits.zext(BitWidth);
1295 RHSKnownZero.zext(BitWidth);
1296 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001297 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001298
1299 // If the sign bit of the input is known set or clear, then we know the
1300 // top bits of the result.
1301
1302 // If the input sign bit is known zero, or if the NewBits are not demanded
1303 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1307 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001308 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 }
1311 break;
1312 }
1313 case Instruction::Add: {
1314 // Figure out what the input bits are. If the top bits of the and result
1315 // are not demanded, then the add doesn't demand them from its input
1316 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001317 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001318
1319 // If there is a constant on the RHS, there are a variety of xformations
1320 // we can do.
1321 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1322 // If null, this should be simplified elsewhere. Some of the xforms here
1323 // won't work if the RHS is zero.
1324 if (RHS->isZero())
1325 break;
1326
1327 // If the top bit of the output is demanded, demand everything from the
1328 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001329 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001330
1331 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001332 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001334 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001335
1336 // If the RHS of the add has bits set that can't affect the input, reduce
1337 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001338 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001340
1341 // Avoid excess work.
1342 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1343 break;
1344
1345 // Turn it into OR if input bits are zero.
1346 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1347 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001348 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001349 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001350 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 }
1352
1353 // We can say something about the output known-zero and known-one bits,
1354 // depending on potential carries from the input constant and the
1355 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1356 // bits set and the RHS constant is 0x01001, then we know we have a known
1357 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1358
1359 // To compute this, we first compute the potential carry bits. These are
1360 // the bits which may be modified. I'm not aware of a better way to do
1361 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001363 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001364
1365 // Now that we know which bits have carries, compute the known-1/0 sets.
1366
1367 // Bits are known one if they are known zero in one operand and one in the
1368 // other, and there is no input carry.
1369 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1370 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1371
1372 // Bits are known zero if they are known zero in both operands and there
1373 // is no input carry.
1374 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1375 } else {
1376 // If the high-bits of this ADD are not demanded, then it does not demand
1377 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001378 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 // Right fill the mask of bits for this ADD to demand the most
1380 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001381 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001382 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1383 LHSKnownZero, LHSKnownOne, Depth+1) ||
1384 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001386 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 }
1388 }
1389 break;
1390 }
1391 case Instruction::Sub:
1392 // If the high-bits of this SUB are not demanded, then it does not demand
1393 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001394 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001395 // Right fill the mask of bits for this SUB to demand the most
1396 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001397 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001398 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001399 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1400 LHSKnownZero, LHSKnownOne, Depth+1) ||
1401 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001402 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001403 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001404 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001405 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1406 // the known zeros and ones.
1407 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 break;
1409 case Instruction::Shl:
1410 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001411 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001412 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001413 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001414 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001415 return I;
1416 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001417 RHSKnownZero <<= ShiftAmt;
1418 RHSKnownOne <<= ShiftAmt;
1419 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001420 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001421 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001422 }
1423 break;
1424 case Instruction::LShr:
1425 // For a logical shift right
1426 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001427 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001428
Reid Spencer8cb68342007-03-12 17:25:59 +00001429 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001430 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001431 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001432 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001433 return I;
1434 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001435 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1436 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001437 if (ShiftAmt) {
1438 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001439 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001440 RHSKnownZero |= HighBits; // high bits known zero.
1441 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001442 }
1443 break;
1444 case Instruction::AShr:
1445 // If this is an arithmetic shift right and only the low-bit is set, we can
1446 // always convert this into a logical shr, even if the shift amount is
1447 // variable. The low bit of the shift cannot be an input sign bit unless
1448 // the shift amount is >= the size of the datatype, which is undefined.
1449 if (DemandedMask == 1) {
1450 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001451 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001452 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001453 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001454 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001455
1456 // If the sign bit is the only bit demanded by this ashr, then there is no
1457 // need to do it, the shift doesn't change the high bit.
1458 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001459 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001460
1461 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001462 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001463
Reid Spencer8cb68342007-03-12 17:25:59 +00001464 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001465 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001466 // If any of the "high bits" are demanded, we should set the sign bit as
1467 // demanded.
1468 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1469 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001470 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001471 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001472 return I;
1473 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001474 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001475 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001476 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1477 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1478
1479 // Handle the sign bits.
1480 APInt SignBit(APInt::getSignBit(BitWidth));
1481 // Adjust to where it is now in the mask.
1482 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1483
1484 // If the input sign bit is known to be zero, or if none of the top bits
1485 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001486 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001487 (HighBits & ~DemandedMask) == HighBits) {
1488 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001489 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001490 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001491 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001492 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1493 RHSKnownOne |= HighBits;
1494 }
1495 }
1496 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001497 case Instruction::SRem:
1498 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001499 APInt RA = Rem->getValue().abs();
1500 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001501 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001502 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001503
Nick Lewycky8e394322008-11-02 02:41:50 +00001504 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001505 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001506 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001507 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001508 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001509
1510 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1511 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001512
1513 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001514
Chris Lattner886ab6c2009-01-31 08:15:18 +00001515 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001516 }
1517 }
1518 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001519 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001520 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1521 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001522 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1523 KnownZero2, KnownOne2, Depth+1) ||
1524 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001525 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001526 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001527
Chris Lattner455e9ab2009-01-21 18:09:24 +00001528 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001529 Leaders = std::max(Leaders,
1530 KnownZero2.countLeadingOnes());
1531 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001532 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001533 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001534 case Instruction::Call:
1535 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1536 switch (II->getIntrinsicID()) {
1537 default: break;
1538 case Intrinsic::bswap: {
1539 // If the only bits demanded come from one byte of the bswap result,
1540 // just shift the input byte into position to eliminate the bswap.
1541 unsigned NLZ = DemandedMask.countLeadingZeros();
1542 unsigned NTZ = DemandedMask.countTrailingZeros();
1543
1544 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1545 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1546 // have 14 leading zeros, round to 8.
1547 NLZ &= ~7;
1548 NTZ &= ~7;
1549 // If we need exactly one byte, we can do this transformation.
1550 if (BitWidth-NLZ-NTZ == 8) {
1551 unsigned ResultBit = NTZ;
1552 unsigned InputBit = BitWidth-NTZ-8;
1553
1554 // Replace this with either a left or right shift to get the byte into
1555 // the right place.
1556 Instruction *NewVal;
1557 if (InputBit > ResultBit)
1558 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001559 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001560 else
1561 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001562 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001563 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001564 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001565 }
1566
1567 // TODO: Could compute known zero/one bits based on the input.
1568 break;
1569 }
1570 }
1571 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001572 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001573 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001574 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001575
1576 // If the client is only demanding bits that we know, return the known
1577 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001578 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1579 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001580 return false;
1581}
1582
Chris Lattner867b99f2006-10-05 06:55:50 +00001583
Mon P Wangaeb06d22008-11-10 04:46:22 +00001584/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001585/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001586/// actually used by the caller. This method analyzes which elements of the
1587/// operand are undef and returns that information in UndefElts.
1588///
1589/// If the information about demanded elements can be used to simplify the
1590/// operation, the operation is simplified, then the resultant value is
1591/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001592Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1593 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001594 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001595 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001596 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001597 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001598
1599 if (isa<UndefValue>(V)) {
1600 // If the entire vector is undefined, just return this info.
1601 UndefElts = EltMask;
1602 return 0;
1603 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1604 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001605 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001606 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001607
Chris Lattner867b99f2006-10-05 06:55:50 +00001608 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001609 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1610 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001611 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001612
1613 std::vector<Constant*> Elts;
1614 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001615 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001616 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001617 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001618 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1619 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001620 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001621 } else { // Otherwise, defined.
1622 Elts.push_back(CP->getOperand(i));
1623 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001624
Chris Lattner867b99f2006-10-05 06:55:50 +00001625 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001626 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001627 return NewCP != CP ? NewCP : 0;
1628 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001629 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001630 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001631
1632 // Check if this is identity. If so, return 0 since we are not simplifying
1633 // anything.
1634 if (DemandedElts == ((1ULL << VWidth) -1))
1635 return 0;
1636
Reid Spencer9d6565a2007-02-15 02:26:10 +00001637 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001638 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001639 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001640 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001641 for (unsigned i = 0; i != VWidth; ++i) {
1642 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1643 Elts.push_back(Elt);
1644 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001645 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001646 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001647 }
1648
Dan Gohman488fbfc2008-09-09 18:11:14 +00001649 // Limit search depth.
1650 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001651 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652
1653 // If multiple users are using the root value, procede with
1654 // simplification conservatively assuming that all elements
1655 // are needed.
1656 if (!V->hasOneUse()) {
1657 // Quit if we find multiple users of a non-root value though.
1658 // They'll be handled when it's their turn to be visited by
1659 // the main instcombine process.
1660 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001661 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001662 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001663
1664 // Conservatively assume that all elements are needed.
1665 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001666 }
1667
1668 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001669 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001670
1671 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001672 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001673 Value *TmpV;
1674 switch (I->getOpcode()) {
1675 default: break;
1676
1677 case Instruction::InsertElement: {
1678 // If this is a variable index, we don't know which element it overwrites.
1679 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001680 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001681 if (Idx == 0) {
1682 // Note that we can't propagate undef elt info, because we don't know
1683 // which elt is getting updated.
1684 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685 UndefElts2, Depth+1);
1686 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687 break;
1688 }
1689
1690 // If this is inserting an element that isn't demanded, remove this
1691 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001692 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001693 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1694 Worklist.Add(I);
1695 return I->getOperand(0);
1696 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001697
1698 // Otherwise, the element inserted overwrites whatever was there, so the
1699 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001700 APInt DemandedElts2 = DemandedElts;
1701 DemandedElts2.clear(IdxNo);
1702 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001703 UndefElts, Depth+1);
1704 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1705
1706 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001707 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001708 break;
1709 }
1710 case Instruction::ShuffleVector: {
1711 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001712 uint64_t LHSVWidth =
1713 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001714 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001715 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001716 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001717 unsigned MaskVal = Shuffle->getMaskValue(i);
1718 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001719 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001720 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001721 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001722 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001723 else
Evan Cheng388df622009-02-03 10:05:09 +00001724 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001725 }
1726 }
1727 }
1728
Nate Begeman7b254672009-02-11 22:36:25 +00001729 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001730 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001731 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001732 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1733
Nate Begeman7b254672009-02-11 22:36:25 +00001734 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001735 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1736 UndefElts3, Depth+1);
1737 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1738
1739 bool NewUndefElts = false;
1740 for (unsigned i = 0; i < VWidth; i++) {
1741 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001742 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001743 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001744 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001745 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001746 NewUndefElts = true;
1747 UndefElts.set(i);
1748 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001749 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001750 if (UndefElts3[MaskVal - LHSVWidth]) {
1751 NewUndefElts = true;
1752 UndefElts.set(i);
1753 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001754 }
1755 }
1756
1757 if (NewUndefElts) {
1758 // Add additional discovered undefs.
1759 std::vector<Constant*> Elts;
1760 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001761 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001762 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001763 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001764 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001765 Shuffle->getMaskValue(i)));
1766 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001767 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001768 MadeChange = true;
1769 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001770 break;
1771 }
Chris Lattner69878332007-04-14 22:29:23 +00001772 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001773 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001774 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1775 if (!VTy) break;
1776 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001777 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001778 unsigned Ratio;
1779
1780 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001781 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001782 // elements as are demanded of us.
1783 Ratio = 1;
1784 InputDemandedElts = DemandedElts;
1785 } else if (VWidth > InVWidth) {
1786 // Untested so far.
1787 break;
1788
1789 // If there are more elements in the result than there are in the source,
1790 // then an input element is live if any of the corresponding output
1791 // elements are live.
1792 Ratio = VWidth/InVWidth;
1793 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001794 if (DemandedElts[OutIdx])
1795 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001796 }
1797 } else {
1798 // Untested so far.
1799 break;
1800
1801 // If there are more elements in the source than there are in the result,
1802 // then an input element is live if the corresponding output element is
1803 // live.
1804 Ratio = InVWidth/VWidth;
1805 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001806 if (DemandedElts[InIdx/Ratio])
1807 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001808 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001809
Chris Lattner69878332007-04-14 22:29:23 +00001810 // div/rem demand all inputs, because they don't want divide by zero.
1811 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1812 UndefElts2, Depth+1);
1813 if (TmpV) {
1814 I->setOperand(0, TmpV);
1815 MadeChange = true;
1816 }
1817
1818 UndefElts = UndefElts2;
1819 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001820 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001821 // If there are more elements in the result than there are in the source,
1822 // then an output element is undef if the corresponding input element is
1823 // undef.
1824 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001825 if (UndefElts2[OutIdx/Ratio])
1826 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001827 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001828 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001829 // If there are more elements in the source than there are in the result,
1830 // then a result element is undef if all of the corresponding input
1831 // elements are undef.
1832 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1833 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001834 if (!UndefElts2[InIdx]) // Not undef?
1835 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001836 }
1837 break;
1838 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001839 case Instruction::And:
1840 case Instruction::Or:
1841 case Instruction::Xor:
1842 case Instruction::Add:
1843 case Instruction::Sub:
1844 case Instruction::Mul:
1845 // div/rem demand all inputs, because they don't want divide by zero.
1846 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1847 UndefElts, Depth+1);
1848 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1849 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1850 UndefElts2, Depth+1);
1851 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1852
1853 // Output elements are undefined if both are undefined. Consider things
1854 // like undef&0. The result is known zero, not undef.
1855 UndefElts &= UndefElts2;
1856 break;
1857
1858 case Instruction::Call: {
1859 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1860 if (!II) break;
1861 switch (II->getIntrinsicID()) {
1862 default: break;
1863
1864 // Binary vector operations that work column-wise. A dest element is a
1865 // function of the corresponding input elements from the two inputs.
1866 case Intrinsic::x86_sse_sub_ss:
1867 case Intrinsic::x86_sse_mul_ss:
1868 case Intrinsic::x86_sse_min_ss:
1869 case Intrinsic::x86_sse_max_ss:
1870 case Intrinsic::x86_sse2_sub_sd:
1871 case Intrinsic::x86_sse2_mul_sd:
1872 case Intrinsic::x86_sse2_min_sd:
1873 case Intrinsic::x86_sse2_max_sd:
1874 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1875 UndefElts, Depth+1);
1876 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1877 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1878 UndefElts2, Depth+1);
1879 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1880
1881 // If only the low elt is demanded and this is a scalarizable intrinsic,
1882 // scalarize it now.
1883 if (DemandedElts == 1) {
1884 switch (II->getIntrinsicID()) {
1885 default: break;
1886 case Intrinsic::x86_sse_sub_ss:
1887 case Intrinsic::x86_sse_mul_ss:
1888 case Intrinsic::x86_sse2_sub_sd:
1889 case Intrinsic::x86_sse2_mul_sd:
1890 // TODO: Lower MIN/MAX/ABS/etc
1891 Value *LHS = II->getOperand(1);
1892 Value *RHS = II->getOperand(2);
1893 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001894 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001895 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001896 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001897 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001898
1899 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001900 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001901 case Intrinsic::x86_sse_sub_ss:
1902 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001903 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001904 II->getName()), *II);
1905 break;
1906 case Intrinsic::x86_sse_mul_ss:
1907 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001908 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001909 II->getName()), *II);
1910 break;
1911 }
1912
1913 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001914 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001915 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001916 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001917 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001918 return New;
1919 }
1920 }
1921
1922 // Output elements are undefined if both are undefined. Consider things
1923 // like undef&0. The result is known zero, not undef.
1924 UndefElts &= UndefElts2;
1925 break;
1926 }
1927 break;
1928 }
1929 }
1930 return MadeChange ? I : 0;
1931}
1932
Dan Gohman45b4e482008-05-19 22:14:15 +00001933
Chris Lattner564a7272003-08-13 19:01:45 +00001934/// AssociativeOpt - Perform an optimization on an associative operator. This
1935/// function is designed to check a chain of associative operators for a
1936/// potential to apply a certain optimization. Since the optimization may be
1937/// applicable if the expression was reassociated, this checks the chain, then
1938/// reassociates the expression as necessary to expose the optimization
1939/// opportunity. This makes use of a special Functor, which must define
1940/// 'shouldApply' and 'apply' methods.
1941///
1942template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001943static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001944 unsigned Opcode = Root.getOpcode();
1945 Value *LHS = Root.getOperand(0);
1946
1947 // Quick check, see if the immediate LHS matches...
1948 if (F.shouldApply(LHS))
1949 return F.apply(Root);
1950
1951 // Otherwise, if the LHS is not of the same opcode as the root, return.
1952 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001953 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001954 // Should we apply this transform to the RHS?
1955 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1956
1957 // If not to the RHS, check to see if we should apply to the LHS...
1958 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1959 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1960 ShouldApply = true;
1961 }
1962
1963 // If the functor wants to apply the optimization to the RHS of LHSI,
1964 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1965 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001966 // Now all of the instructions are in the current basic block, go ahead
1967 // and perform the reassociation.
1968 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1969
1970 // First move the selected RHS to the LHS of the root...
1971 Root.setOperand(0, LHSI->getOperand(1));
1972
1973 // Make what used to be the LHS of the root be the user of the root...
1974 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001975 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001976 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001977 return 0;
1978 }
Chris Lattner65725312004-04-16 18:08:07 +00001979 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001980 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001981 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001982 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001983 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001984
1985 // Now propagate the ExtraOperand down the chain of instructions until we
1986 // get to LHSI.
1987 while (TmpLHSI != LHSI) {
1988 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001989 // Move the instruction to immediately before the chain we are
1990 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001991 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001992 ARI = NextLHSI;
1993
Chris Lattner564a7272003-08-13 19:01:45 +00001994 Value *NextOp = NextLHSI->getOperand(1);
1995 NextLHSI->setOperand(1, ExtraOperand);
1996 TmpLHSI = NextLHSI;
1997 ExtraOperand = NextOp;
1998 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001999
Chris Lattner564a7272003-08-13 19:01:45 +00002000 // Now that the instructions are reassociated, have the functor perform
2001 // the transformation...
2002 return F.apply(Root);
2003 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002004
Chris Lattner564a7272003-08-13 19:01:45 +00002005 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2006 }
2007 return 0;
2008}
2009
Dan Gohman844731a2008-05-13 00:00:25 +00002010namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002011
Nick Lewycky02d639f2008-05-23 04:34:58 +00002012// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002013struct AddRHS {
2014 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00002015 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002016 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2017 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002018 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00002019 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002020 }
2021};
2022
2023// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2024// iff C1&C2 == 0
2025struct AddMaskingAnd {
2026 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00002027 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002028 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002029 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00002030 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002031 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002032 }
2033 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002035 }
2036};
2037
Dan Gohman844731a2008-05-13 00:00:25 +00002038}
2039
Chris Lattner6e7ba452005-01-01 16:22:27 +00002040static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002041 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00002042 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00002043 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00002044
Chris Lattner2eefe512004-04-09 19:05:30 +00002045 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002046 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2047 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002048
Chris Lattner2eefe512004-04-09 19:05:30 +00002049 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2050 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00002051 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2052 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002053 }
2054
2055 Value *Op0 = SO, *Op1 = ConstOperand;
2056 if (!ConstIsRHS)
2057 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00002058
Chris Lattner6e7ba452005-01-01 16:22:27 +00002059 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00002060 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2061 SO->getName()+".op");
2062 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2063 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2064 SO->getName()+".cmp");
2065 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2066 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2067 SO->getName()+".cmp");
2068 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00002069}
2070
2071// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2072// constant as the other operand, try to fold the binary operator into the
2073// select arguments. This also works for Cast instructions, which obviously do
2074// not have a second operand.
2075static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2076 InstCombiner *IC) {
2077 // Don't modify shared select instructions
2078 if (!SI->hasOneUse()) return 0;
2079 Value *TV = SI->getOperand(1);
2080 Value *FV = SI->getOperand(2);
2081
2082 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002083 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002084 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002085
Chris Lattner6e7ba452005-01-01 16:22:27 +00002086 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2087 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2088
Gabor Greif051a9502008-04-06 20:25:17 +00002089 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2090 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002091 }
2092 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002093}
2094
Chris Lattner4e998b22004-09-29 05:07:12 +00002095
Chris Lattner5d1704d2009-09-27 19:57:57 +00002096/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2097/// has a PHI node as operand #0, see if we can fold the instruction into the
2098/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002099///
2100/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2101/// that would normally be unprofitable because they strongly encourage jump
2102/// threading.
2103Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2104 bool AllowAggressive) {
2105 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002106 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002107 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002108 if (NumPHIValues == 0 ||
2109 // We normally only transform phis with a single use, unless we're trying
2110 // hard to make jump threading happen.
2111 (!PN->hasOneUse() && !AllowAggressive))
2112 return 0;
2113
2114
Chris Lattner5d1704d2009-09-27 19:57:57 +00002115 // Check to see if all of the operands of the PHI are simple constants
2116 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002117 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2118 // bail out. We don't do arbitrary constant expressions here because moving
2119 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002120 BasicBlock *NonConstBB = 0;
2121 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002122 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2123 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002124 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002125 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002126 NonConstBB = PN->getIncomingBlock(i);
2127
2128 // If the incoming non-constant value is in I's block, we have an infinite
2129 // loop.
2130 if (NonConstBB == I.getParent())
2131 return 0;
2132 }
2133
2134 // If there is exactly one non-constant value, we can insert a copy of the
2135 // operation in that block. However, if this is a critical edge, we would be
2136 // inserting the computation one some other paths (e.g. inside a loop). Only
2137 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002138 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002139 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2140 if (!BI || !BI->isUnconditional()) return 0;
2141 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002142
2143 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002144 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002145 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002146 InsertNewInstBefore(NewPN, *PN);
2147 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002148
2149 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002150 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2151 // We only currently try to fold the condition of a select when it is a phi,
2152 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002153 Value *TrueV = SI->getTrueValue();
2154 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002155 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002156 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002157 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002158 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2159 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002160 Value *InV = 0;
2161 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002162 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002163 } else {
2164 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002165 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2166 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002167 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002168 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002169 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002170 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002171 }
2172 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002173 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002174 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002175 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002176 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002177 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002178 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002179 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002180 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002181 } else {
2182 assert(PN->getIncomingBlock(i) == NonConstBB);
2183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002184 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002185 PN->getIncomingValue(i), C, "phitmp",
2186 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002187 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002188 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002189 CI->getPredicate(),
2190 PN->getIncomingValue(i), C, "phitmp",
2191 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002192 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002193 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002194
2195 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002196 }
2197 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002198 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002199 } else {
2200 CastInst *CI = cast<CastInst>(&I);
2201 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002202 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002203 Value *InV;
2204 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002205 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002206 } else {
2207 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002208 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002209 I.getType(), "phitmp",
2210 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002211 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002212 }
2213 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002214 }
2215 }
2216 return ReplaceInstUsesWith(I, NewPN);
2217}
2218
Chris Lattner2454a2e2008-01-29 06:52:45 +00002219
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002220/// WillNotOverflowSignedAdd - Return true if we can prove that:
2221/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2222/// This basically requires proving that the add in the original type would not
2223/// overflow to change the sign bit or have a carry out.
2224bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2225 // There are different heuristics we can use for this. Here are some simple
2226 // ones.
2227
2228 // Add has the property that adding any two 2's complement numbers can only
2229 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002230 // have at least two sign bits, we know that the addition of the two values
2231 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002232 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2233 return true;
2234
2235
2236 // If one of the operands only has one non-zero bit, and if the other operand
2237 // has a known-zero bit in a more significant place than it (not including the
2238 // sign bit) the ripple may go up to and fill the zero, but won't change the
2239 // sign. For example, (X & ~4) + 1.
2240
2241 // TODO: Implement.
2242
2243 return false;
2244}
2245
Chris Lattner2454a2e2008-01-29 06:52:45 +00002246
Chris Lattner7e708292002-06-25 16:13:24 +00002247Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002248 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002249 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002250
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002251 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2252 I.hasNoUnsignedWrap(), TD))
2253 return ReplaceInstUsesWith(I, V);
2254
2255
Chris Lattner66331a42004-04-10 22:01:55 +00002256 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002257 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002258 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002259 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002260 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002261 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002262 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002263
2264 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2265 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002266 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002267 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002268
Eli Friedman709b33d2009-07-13 22:27:52 +00002269 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002270 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002271 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002272 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002273 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002274
2275 if (isa<PHINode>(LHS))
2276 if (Instruction *NV = FoldOpIntoPhi(I))
2277 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002278
Chris Lattner4f637d42006-01-06 17:59:59 +00002279 ConstantInt *XorRHS = 0;
2280 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002281 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002282 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002283 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002284 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002285
Zhou Sheng4351c642007-04-02 08:20:41 +00002286 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002287 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2288 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002289 do {
2290 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002291 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2292 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002293 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2294 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002295 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002296 if (!MaskedValueIsZero(XorLHS,
2297 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002298 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002299 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002300 }
2301 }
2302 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002303 C0080Val = APIntOps::lshr(C0080Val, Size);
2304 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2305 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002306
Reid Spencer35c38852007-03-28 01:36:16 +00002307 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002308 // with funny bit widths then this switch statement should be removed. It
2309 // is just here to get the size of the "middle" type back up to something
2310 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002311 const Type *MiddleType = 0;
2312 switch (Size) {
2313 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002314 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2315 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2316 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002317 }
2318 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002319 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002320 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002321 }
2322 }
Chris Lattner66331a42004-04-10 22:01:55 +00002323 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002324
Owen Anderson1d0be152009-08-13 21:58:54 +00002325 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002326 return BinaryOperator::CreateXor(LHS, RHS);
2327
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002328 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002329 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002330 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002331 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002332
2333 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2334 if (RHSI->getOpcode() == Instruction::Sub)
2335 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2336 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2337 }
2338 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2339 if (LHSI->getOpcode() == Instruction::Sub)
2340 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2341 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2342 }
Robert Bocchino71698282004-07-27 21:02:21 +00002343 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002344
Chris Lattner5c4afb92002-05-08 22:46:53 +00002345 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002346 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002347 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002348 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002349 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002350 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002351 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002352 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002353 }
2354
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002356 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002357
2358 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002359 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002360 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002361 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002362
Misha Brukmanfd939082005-04-21 23:48:37 +00002363
Chris Lattner50af16a2004-11-13 19:50:12 +00002364 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002365 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002366 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002367 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002368
2369 // X*C1 + X*C2 --> X * (C1+C2)
2370 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002371 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002372 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002373 }
2374
2375 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002376 if (dyn_castFoldableMul(RHS, C2) == LHS)
2377 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002378
Chris Lattnere617c9e2007-01-05 02:17:46 +00002379 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002380 if (dyn_castNotVal(LHS) == RHS ||
2381 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002382 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002383
Chris Lattnerad3448c2003-02-18 19:57:07 +00002384
Chris Lattner564a7272003-08-13 19:01:45 +00002385 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002386 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2387 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002388 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002389
2390 // A+B --> A|B iff A and B have no bits set in common.
2391 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2392 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2393 APInt LHSKnownOne(IT->getBitWidth(), 0);
2394 APInt LHSKnownZero(IT->getBitWidth(), 0);
2395 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2396 if (LHSKnownZero != 0) {
2397 APInt RHSKnownOne(IT->getBitWidth(), 0);
2398 APInt RHSKnownZero(IT->getBitWidth(), 0);
2399 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2400
2401 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002402 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002403 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002404 }
2405 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002406
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002407 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002408 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002409 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002410 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2411 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002412 if (W != Y) {
2413 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002414 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002415 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002416 std::swap(W, X);
2417 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002418 std::swap(Y, Z);
2419 std::swap(W, X);
2420 }
2421 }
2422
2423 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002424 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002425 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002426 }
2427 }
2428 }
2429
Chris Lattner6b032052003-10-02 15:11:26 +00002430 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002431 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002432 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002433 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002434
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002435 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002436 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002437 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002438 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002439 if (Anded == CRHS) {
2440 // See if all bits from the first bit set in the Add RHS up are included
2441 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002442 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002443
2444 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002445 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002446
2447 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002448 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002449
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002450 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2451 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002452 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002453 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002454 }
2455 }
2456 }
2457
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002458 // Try to fold constant add into select arguments.
2459 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002460 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002461 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002462 }
2463
Chris Lattner42790482007-12-20 01:56:58 +00002464 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002465 {
2466 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002467 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002468 if (!SI) {
2469 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002470 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002471 }
Chris Lattner42790482007-12-20 01:56:58 +00002472 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002473 Value *TV = SI->getTrueValue();
2474 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002475 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002476
2477 // Can we fold the add into the argument of the select?
2478 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002479 if (match(FV, m_Zero()) &&
2480 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002481 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002482 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002483 if (match(TV, m_Zero()) &&
2484 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002485 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002486 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002487 }
2488 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002489
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002490 // Check for (add (sext x), y), see if we can merge this into an
2491 // integer add followed by a sext.
2492 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2493 // (add (sext x), cst) --> (sext (add x, cst'))
2494 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2495 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002496 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002497 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002498 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002499 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2500 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002501 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2502 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002503 return new SExtInst(NewAdd, I.getType());
2504 }
2505 }
2506
2507 // (add (sext x), (sext y)) --> (sext (add int x, y))
2508 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2509 // Only do this if x/y have the same type, if at last one of them has a
2510 // single use (so we don't increase the number of sexts), and if the
2511 // integer add will not overflow.
2512 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2513 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2514 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2515 RHSConv->getOperand(0))) {
2516 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002517 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2518 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002519 return new SExtInst(NewAdd, I.getType());
2520 }
2521 }
2522 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002523
2524 return Changed ? &I : 0;
2525}
2526
2527Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2528 bool Changed = SimplifyCommutative(I);
2529 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2530
2531 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2532 // X + 0 --> X
2533 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002534 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002535 (I.getType())->getValueAPF()))
2536 return ReplaceInstUsesWith(I, LHS);
2537 }
2538
2539 if (isa<PHINode>(LHS))
2540 if (Instruction *NV = FoldOpIntoPhi(I))
2541 return NV;
2542 }
2543
2544 // -A + B --> B - A
2545 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002546 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002547 return BinaryOperator::CreateFSub(RHS, LHSV);
2548
2549 // A + -B --> A - B
2550 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002551 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002552 return BinaryOperator::CreateFSub(LHS, V);
2553
2554 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2555 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2556 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2557 return ReplaceInstUsesWith(I, LHS);
2558
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002559 // Check for (add double (sitofp x), y), see if we can merge this into an
2560 // integer add followed by a promotion.
2561 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2562 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2563 // ... if the constant fits in the integer value. This is useful for things
2564 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2565 // requires a constant pool load, and generally allows the add to be better
2566 // instcombined.
2567 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2568 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002569 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002570 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002571 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002572 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2573 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002574 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2575 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002576 return new SIToFPInst(NewAdd, I.getType());
2577 }
2578 }
2579
2580 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2581 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2582 // Only do this if x/y have the same type, if at last one of them has a
2583 // single use (so we don't increase the number of int->fp conversions),
2584 // and if the integer add will not overflow.
2585 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2586 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2587 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2588 RHSConv->getOperand(0))) {
2589 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002590 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002591 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002592 return new SIToFPInst(NewAdd, I.getType());
2593 }
2594 }
2595 }
2596
Chris Lattner7e708292002-06-25 16:13:24 +00002597 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002598}
2599
Chris Lattner092543c2009-11-04 08:05:20 +00002600
2601/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2602/// code necessary to compute the offset from the base pointer (without adding
2603/// in the base pointer). Return the result as a signed integer of intptr size.
2604static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2605 TargetData &TD = *IC.getTargetData();
2606 gep_type_iterator GTI = gep_type_begin(GEP);
2607 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2608 Value *Result = Constant::getNullValue(IntPtrTy);
2609
2610 // Build a mask for high order bits.
2611 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2612 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2613
2614 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2615 ++i, ++GTI) {
2616 Value *Op = *i;
2617 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2618 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2619 if (OpC->isZero()) continue;
2620
2621 // Handle a struct index, which adds its field offset to the pointer.
2622 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2623 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2624
2625 Result = IC.Builder->CreateAdd(Result,
2626 ConstantInt::get(IntPtrTy, Size),
2627 GEP->getName()+".offs");
2628 continue;
2629 }
2630
2631 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2632 Constant *OC =
2633 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2634 Scale = ConstantExpr::getMul(OC, Scale);
2635 // Emit an add instruction.
2636 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2637 continue;
2638 }
2639 // Convert to correct type.
2640 if (Op->getType() != IntPtrTy)
2641 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2642 if (Size != 1) {
2643 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2644 // We'll let instcombine(mul) convert this to a shl if possible.
2645 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2646 }
2647
2648 // Emit an add instruction.
2649 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2650 }
2651 return Result;
2652}
2653
2654
2655/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2656/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2657/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2658/// be complex, and scales are involved. The above expression would also be
2659/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2660/// This later form is less amenable to optimization though, and we are allowed
2661/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2662///
2663/// If we can't emit an optimized form for this expression, this returns null.
2664///
2665static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2666 InstCombiner &IC) {
2667 TargetData &TD = *IC.getTargetData();
2668 gep_type_iterator GTI = gep_type_begin(GEP);
2669
2670 // Check to see if this gep only has a single variable index. If so, and if
2671 // any constant indices are a multiple of its scale, then we can compute this
2672 // in terms of the scale of the variable index. For example, if the GEP
2673 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2674 // because the expression will cross zero at the same point.
2675 unsigned i, e = GEP->getNumOperands();
2676 int64_t Offset = 0;
2677 for (i = 1; i != e; ++i, ++GTI) {
2678 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2679 // Compute the aggregate offset of constant indices.
2680 if (CI->isZero()) continue;
2681
2682 // Handle a struct index, which adds its field offset to the pointer.
2683 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2684 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2685 } else {
2686 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2687 Offset += Size*CI->getSExtValue();
2688 }
2689 } else {
2690 // Found our variable index.
2691 break;
2692 }
2693 }
2694
2695 // If there are no variable indices, we must have a constant offset, just
2696 // evaluate it the general way.
2697 if (i == e) return 0;
2698
2699 Value *VariableIdx = GEP->getOperand(i);
2700 // Determine the scale factor of the variable element. For example, this is
2701 // 4 if the variable index is into an array of i32.
2702 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2703
2704 // Verify that there are no other variable indices. If so, emit the hard way.
2705 for (++i, ++GTI; i != e; ++i, ++GTI) {
2706 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2707 if (!CI) return 0;
2708
2709 // Compute the aggregate offset of constant indices.
2710 if (CI->isZero()) continue;
2711
2712 // Handle a struct index, which adds its field offset to the pointer.
2713 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2714 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2715 } else {
2716 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2717 Offset += Size*CI->getSExtValue();
2718 }
2719 }
2720
2721 // Okay, we know we have a single variable index, which must be a
2722 // pointer/array/vector index. If there is no offset, life is simple, return
2723 // the index.
2724 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2725 if (Offset == 0) {
2726 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2727 // we don't need to bother extending: the extension won't affect where the
2728 // computation crosses zero.
2729 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2730 VariableIdx = new TruncInst(VariableIdx,
2731 TD.getIntPtrType(VariableIdx->getContext()),
2732 VariableIdx->getName(), &I);
2733 return VariableIdx;
2734 }
2735
2736 // Otherwise, there is an index. The computation we will do will be modulo
2737 // the pointer size, so get it.
2738 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2739
2740 Offset &= PtrSizeMask;
2741 VariableScale &= PtrSizeMask;
2742
2743 // To do this transformation, any constant index must be a multiple of the
2744 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2745 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2746 // multiple of the variable scale.
2747 int64_t NewOffs = Offset / (int64_t)VariableScale;
2748 if (Offset != NewOffs*(int64_t)VariableScale)
2749 return 0;
2750
2751 // Okay, we can do this evaluation. Start by converting the index to intptr.
2752 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2753 if (VariableIdx->getType() != IntPtrTy)
2754 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2755 true /*SExt*/,
2756 VariableIdx->getName(), &I);
2757 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2758 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2759}
2760
2761
2762/// Optimize pointer differences into the same array into a size. Consider:
2763/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2764/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2765///
2766Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2767 const Type *Ty) {
2768 assert(TD && "Must have target data info for this");
2769
2770 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2771 // this.
2772 bool Swapped;
2773 GetElementPtrInst *GEP;
2774
2775 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2776 GEP->getOperand(0) == RHS)
2777 Swapped = false;
2778 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2779 GEP->getOperand(0) == LHS)
2780 Swapped = true;
2781 else
2782 return 0;
2783
2784 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2785
2786 // Emit the offset of the GEP and an intptr_t.
2787 Value *Result = EmitGEPOffset(GEP, *this);
2788
2789 // If we have p - gep(p, ...) then we have to negate the result.
2790 if (Swapped)
2791 Result = Builder->CreateNeg(Result, "diff.neg");
2792
2793 return Builder->CreateIntCast(Result, Ty, true);
2794}
2795
2796
Chris Lattner7e708292002-06-25 16:13:24 +00002797Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002798 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002799
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002800 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002801 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002802
Chris Lattner3bf68152009-12-21 04:04:05 +00002803 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2804 if (Value *V = dyn_castNegVal(Op1)) {
2805 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2806 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2807 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2808 return Res;
2809 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002810
Chris Lattnere87597f2004-10-16 18:11:37 +00002811 if (isa<UndefValue>(Op0))
2812 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2813 if (isa<UndefValue>(Op1))
2814 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002815 if (I.getType() == Type::getInt1Ty(*Context))
2816 return BinaryOperator::CreateXor(Op0, Op1);
2817
Chris Lattnerd65460f2003-11-05 01:06:05 +00002818 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002819 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002820 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002821 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002822
Chris Lattnerd65460f2003-11-05 01:06:05 +00002823 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002824 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002825 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002826 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002827
Chris Lattner76b7a062007-01-15 07:02:54 +00002828 // -(X >>u 31) -> (X >>s 31)
2829 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002830 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002831 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002832 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002833 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002834 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002835 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002836 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002837 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002838 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002839 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002840 }
2841 }
Chris Lattner092543c2009-11-04 08:05:20 +00002842 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002843 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2844 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002845 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002846 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002847 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002848 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002849 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002850 }
2851 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002852 }
2853 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002854 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002855
2856 // Try to fold constant sub into select arguments.
2857 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002858 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002859 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002860
2861 // C - zext(bool) -> bool ? C - 1 : C
2862 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002863 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002864 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002865 }
2866
Chris Lattner43d84d62005-04-07 16:15:25 +00002867 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002868 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002869 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002870 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002871 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002872 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002873 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002874 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002875 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2876 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2877 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002878 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002879 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002880 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002881 }
2882
Chris Lattnerfd059242003-10-15 16:48:29 +00002883 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002884 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2885 // is not used by anyone else...
2886 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002887 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002888 // Swap the two operands of the subexpr...
2889 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2890 Op1I->setOperand(0, IIOp1);
2891 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002892
Chris Lattnera2881962003-02-18 19:28:33 +00002893 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002894 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002895 }
2896
2897 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2898 //
2899 if (Op1I->getOpcode() == Instruction::And &&
2900 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2901 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2902
Chris Lattner74381062009-08-30 07:44:24 +00002903 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002904 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002905 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002906
Reid Spencerac5209e2006-10-16 23:08:08 +00002907 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002908 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002909 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002910 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002911 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002912 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002913 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002914
Chris Lattnerad3448c2003-02-18 19:57:07 +00002915 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002916 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002917 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002918 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002919 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002920 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002921 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002922 }
Chris Lattner40371712002-05-09 01:29:19 +00002923 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002924 }
Chris Lattnera2881962003-02-18 19:28:33 +00002925
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002926 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2927 if (Op0I->getOpcode() == Instruction::Add) {
2928 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2929 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2930 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2931 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2932 } else if (Op0I->getOpcode() == Instruction::Sub) {
2933 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002934 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002935 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002936 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002937 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002938
Chris Lattner50af16a2004-11-13 19:50:12 +00002939 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002940 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002941 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002942 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002943
Chris Lattner50af16a2004-11-13 19:50:12 +00002944 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002945 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002946 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002947 }
Chris Lattner092543c2009-11-04 08:05:20 +00002948
2949 // Optimize pointer differences into the same array into a size. Consider:
2950 // &A[10] - &A[0]: we should compile this to "10".
2951 if (TD) {
2952 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2953 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2954 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2955 RHS->getOperand(0),
2956 I.getType()))
2957 return ReplaceInstUsesWith(I, Res);
2958
2959 // trunc(p)-trunc(q) -> trunc(p-q)
2960 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2961 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2962 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2963 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2964 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2965 RHS->getOperand(0),
2966 I.getType()))
2967 return ReplaceInstUsesWith(I, Res);
2968 }
2969
Chris Lattner3f5b8772002-05-06 16:14:14 +00002970 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002971}
2972
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002973Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2975
2976 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002977 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002978 return BinaryOperator::CreateFAdd(Op0, V);
2979
2980 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2981 if (Op1I->getOpcode() == Instruction::FAdd) {
2982 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002983 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002984 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002985 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002986 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002987 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002988 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002989 }
2990
2991 return 0;
2992}
2993
Chris Lattnera0141b92007-07-15 20:42:37 +00002994/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2995/// comparison only checks the sign bit. If it only checks the sign bit, set
2996/// TrueIfSigned if the result of the comparison is true when the input value is
2997/// signed.
2998static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2999 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003000 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003001 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3002 TrueIfSigned = true;
3003 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003004 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3005 TrueIfSigned = true;
3006 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003007 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3008 TrueIfSigned = false;
3009 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003010 case ICmpInst::ICMP_UGT:
3011 // True if LHS u> RHS and RHS == high-bit-mask - 1
3012 TrueIfSigned = true;
3013 return RHS->getValue() ==
3014 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3015 case ICmpInst::ICMP_UGE:
3016 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3017 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00003018 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00003019 default:
3020 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003021 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003022}
3023
Chris Lattner7e708292002-06-25 16:13:24 +00003024Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003025 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003027
Chris Lattnera2498472009-10-11 21:36:10 +00003028 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003029 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003030
Chris Lattner8af304a2009-10-11 07:53:15 +00003031 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00003032 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3033 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003034
3035 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003036 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003037 if (SI->getOpcode() == Instruction::Shl)
3038 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003039 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003040 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003041
Zhou Sheng843f07672007-04-19 05:39:12 +00003042 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00003043 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00003044 if (CI->equalsInt(1)) // X * 1 == X
3045 return ReplaceInstUsesWith(I, Op0);
3046 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003047 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003048
Zhou Sheng97b52c22007-03-29 01:57:21 +00003049 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003050 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003051 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003052 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003053 }
Chris Lattnera2498472009-10-11 21:36:10 +00003054 } else if (isa<VectorType>(Op1C->getType())) {
3055 if (Op1C->isNullValue())
3056 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00003057
Chris Lattnera2498472009-10-11 21:36:10 +00003058 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003059 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003060 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00003061
3062 // As above, vector X*splat(1.0) -> X in all defined cases.
3063 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3065 if (CI->equalsInt(1))
3066 return ReplaceInstUsesWith(I, Op0);
3067 }
3068 }
Chris Lattnera2881962003-02-18 19:28:33 +00003069 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003070
3071 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3072 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003073 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003074 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003075 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3076 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003077 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003078
3079 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003080
3081 // Try to fold constant mul into select arguments.
3082 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003083 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003084 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003085
3086 if (isa<PHINode>(Op0))
3087 if (Instruction *NV = FoldOpIntoPhi(I))
3088 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003089 }
3090
Dan Gohman186a6362009-08-12 16:04:34 +00003091 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003092 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003093 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003094
Nick Lewycky0c730792008-11-21 07:33:58 +00003095 // (X / Y) * Y = X - (X % Y)
3096 // (X / Y) * -Y = (X % Y) - X
3097 {
Chris Lattnera2498472009-10-11 21:36:10 +00003098 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003099 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3100 if (!BO ||
3101 (BO->getOpcode() != Instruction::UDiv &&
3102 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003103 Op1C = Op0;
3104 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003105 }
Chris Lattnera2498472009-10-11 21:36:10 +00003106 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003107 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003108 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003109 (BO->getOpcode() == Instruction::UDiv ||
3110 BO->getOpcode() == Instruction::SDiv)) {
3111 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3112
Dan Gohmanfa94b942009-08-12 16:33:09 +00003113 // If the division is exact, X % Y is zero.
3114 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3115 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003116 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003117 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003118 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003119 }
3120
Chris Lattner74381062009-08-30 07:44:24 +00003121 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003122 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003123 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003124 else
Chris Lattner74381062009-08-30 07:44:24 +00003125 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003126 Rem->takeName(BO);
3127
Chris Lattnera2498472009-10-11 21:36:10 +00003128 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003129 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003130 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003131 }
3132 }
3133
Chris Lattner8af304a2009-10-11 07:53:15 +00003134 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003135 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003136 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003137
Chris Lattner8af304a2009-10-11 07:53:15 +00003138 // X*(1 << Y) --> X << Y
3139 // (1 << Y)*X --> X << Y
3140 {
3141 Value *Y;
3142 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003143 return BinaryOperator::CreateShl(Op1, Y);
3144 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003145 return BinaryOperator::CreateShl(Op0, Y);
3146 }
3147
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003148 // If one of the operands of the multiply is a cast from a boolean value, then
3149 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003150 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3151 if (!isa<VectorType>(I.getType())) {
3152 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003153 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003154
Chris Lattnerd2c58362009-10-11 21:29:45 +00003155 Value *BoolCast = 0, *OtherOp = 0;
3156 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003157 BoolCast = Op0, OtherOp = Op1;
3158 else if (MaskedValueIsZero(Op1, Negative2))
3159 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003160
Chris Lattner0036e3a2009-10-11 21:22:21 +00003161 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003162 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3163 BoolCast, "tmp");
3164 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003165 }
3166 }
3167
Chris Lattner7e708292002-06-25 16:13:24 +00003168 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003169}
3170
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003171Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3172 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003173 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003174
3175 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003176 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3177 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003178 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3179 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3180 if (Op1F->isExactlyValue(1.0))
3181 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003182 } else if (isa<VectorType>(Op1C->getType())) {
3183 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003184 // As above, vector X*splat(1.0) -> X in all defined cases.
3185 if (Constant *Splat = Op1V->getSplatValue()) {
3186 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3187 if (F->isExactlyValue(1.0))
3188 return ReplaceInstUsesWith(I, Op0);
3189 }
3190 }
3191 }
3192
3193 // Try to fold constant mul into select arguments.
3194 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3195 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3196 return R;
3197
3198 if (isa<PHINode>(Op0))
3199 if (Instruction *NV = FoldOpIntoPhi(I))
3200 return NV;
3201 }
3202
Dan Gohman186a6362009-08-12 16:04:34 +00003203 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003204 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003205 return BinaryOperator::CreateFMul(Op0v, Op1v);
3206
3207 return Changed ? &I : 0;
3208}
3209
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003210/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3211/// instruction.
3212bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3213 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3214
3215 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3216 int NonNullOperand = -1;
3217 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3218 if (ST->isNullValue())
3219 NonNullOperand = 2;
3220 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3221 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3222 if (ST->isNullValue())
3223 NonNullOperand = 1;
3224
3225 if (NonNullOperand == -1)
3226 return false;
3227
3228 Value *SelectCond = SI->getOperand(0);
3229
3230 // Change the div/rem to use 'Y' instead of the select.
3231 I.setOperand(1, SI->getOperand(NonNullOperand));
3232
3233 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3234 // problem. However, the select, or the condition of the select may have
3235 // multiple uses. Based on our knowledge that the operand must be non-zero,
3236 // propagate the known value for the select into other uses of it, and
3237 // propagate a known value of the condition into its other users.
3238
3239 // If the select and condition only have a single use, don't bother with this,
3240 // early exit.
3241 if (SI->use_empty() && SelectCond->hasOneUse())
3242 return true;
3243
3244 // Scan the current block backward, looking for other uses of SI.
3245 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3246
3247 while (BBI != BBFront) {
3248 --BBI;
3249 // If we found a call to a function, we can't assume it will return, so
3250 // information from below it cannot be propagated above it.
3251 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3252 break;
3253
3254 // Replace uses of the select or its condition with the known values.
3255 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3256 I != E; ++I) {
3257 if (*I == SI) {
3258 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003259 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003260 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003261 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3262 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003263 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003264 }
3265 }
3266
3267 // If we past the instruction, quit looking for it.
3268 if (&*BBI == SI)
3269 SI = 0;
3270 if (&*BBI == SelectCond)
3271 SelectCond = 0;
3272
3273 // If we ran out of things to eliminate, break out of the loop.
3274 if (SelectCond == 0 && SI == 0)
3275 break;
3276
3277 }
3278 return true;
3279}
3280
3281
Reid Spencer1628cec2006-10-26 06:15:43 +00003282/// This function implements the transforms on div instructions that work
3283/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3284/// used by the visitors to those instructions.
3285/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003286Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003287 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003288
Chris Lattner50b2ca42008-02-19 06:12:18 +00003289 // undef / X -> 0 for integer.
3290 // undef / X -> undef for FP (the undef could be a snan).
3291 if (isa<UndefValue>(Op0)) {
3292 if (Op0->getType()->isFPOrFPVector())
3293 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003295 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003296
3297 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003298 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003299 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003300
Reid Spencer1628cec2006-10-26 06:15:43 +00003301 return 0;
3302}
Misha Brukmanfd939082005-04-21 23:48:37 +00003303
Reid Spencer1628cec2006-10-26 06:15:43 +00003304/// This function implements the transforms common to both integer division
3305/// instructions (udiv and sdiv). It is called by the visitors to those integer
3306/// division instructions.
3307/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003308Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3310
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003311 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003312 if (Op0 == Op1) {
3313 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003314 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003315 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003316 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003317 }
3318
Owen Andersoneed707b2009-07-24 23:12:02 +00003319 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003320 return ReplaceInstUsesWith(I, CI);
3321 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003322
Reid Spencer1628cec2006-10-26 06:15:43 +00003323 if (Instruction *Common = commonDivTransforms(I))
3324 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003325
3326 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3327 // This does not apply for fdiv.
3328 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3329 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003330
3331 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3332 // div X, 1 == X
3333 if (RHS->equalsInt(1))
3334 return ReplaceInstUsesWith(I, Op0);
3335
3336 // (X / C1) / C2 -> X / (C1*C2)
3337 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3338 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3339 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003340 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003341 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003342 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003343 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003344 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003345 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003346 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003347
Reid Spencerbca0e382007-03-23 20:05:17 +00003348 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003349 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3350 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3351 return R;
3352 if (isa<PHINode>(Op0))
3353 if (Instruction *NV = FoldOpIntoPhi(I))
3354 return NV;
3355 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003356 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003357
Chris Lattnera2881962003-02-18 19:28:33 +00003358 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003359 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003360 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003362
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003363 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003364 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003365 return ReplaceInstUsesWith(I, Op0);
3366
Nick Lewycky895f0852008-11-27 20:21:08 +00003367 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3368 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3369 // div X, 1 == X
3370 if (X->isOne())
3371 return ReplaceInstUsesWith(I, Op0);
3372 }
3373
Reid Spencer1628cec2006-10-26 06:15:43 +00003374 return 0;
3375}
3376
3377Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3378 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3379
3380 // Handle the integer div common cases
3381 if (Instruction *Common = commonIDivTransforms(I))
3382 return Common;
3383
Reid Spencer1628cec2006-10-26 06:15:43 +00003384 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003385 // X udiv C^2 -> X >> C
3386 // Check to see if this is an unsigned division with an exact power of 2,
3387 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003388 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003389 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003390 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003391
3392 // X udiv C, where C >= signbit
3393 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003394 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003395 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003396 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003397 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003398 }
3399
3400 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003401 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003402 if (RHSI->getOpcode() == Instruction::Shl &&
3403 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003404 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003405 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003406 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003407 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003408 if (uint32_t C2 = C1.logBase2())
3409 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003410 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003411 }
3412 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003413 }
3414
Reid Spencer1628cec2006-10-26 06:15:43 +00003415 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3416 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003417 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003418 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003419 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003420 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003421 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003422 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003423 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003424 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003425 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003426 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003427
3428 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003429 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003430 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003431
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003432 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003433 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003434 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003435 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003436 return 0;
3437}
3438
Reid Spencer1628cec2006-10-26 06:15:43 +00003439Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3440 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3441
3442 // Handle the integer div common cases
3443 if (Instruction *Common = commonIDivTransforms(I))
3444 return Common;
3445
3446 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3447 // sdiv X, -1 == -X
3448 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003449 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003450
Dan Gohmanfa94b942009-08-12 16:33:09 +00003451 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003452 if (cast<SDivOperator>(&I)->isExact() &&
3453 RHS->getValue().isNonNegative() &&
3454 RHS->getValue().isPowerOf2()) {
3455 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3456 RHS->getValue().exactLogBase2());
3457 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3458 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003459
3460 // -X/C --> X/-C provided the negation doesn't overflow.
3461 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3462 if (isa<Constant>(Sub->getOperand(0)) &&
3463 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003464 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003465 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3466 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003467 }
3468
3469 // If the sign bits of both operands are zero (i.e. we can prove they are
3470 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003471 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003472 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003473 if (MaskedValueIsZero(Op0, Mask)) {
3474 if (MaskedValueIsZero(Op1, Mask)) {
3475 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3476 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3477 }
3478 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003479 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003480 ShiftedInt->getValue().isPowerOf2()) {
3481 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3482 // Safe because the only negative value (1 << Y) can take on is
3483 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3484 // the sign bit set.
3485 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3486 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003487 }
Eli Friedman8be17392009-07-18 09:53:21 +00003488 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003489
3490 return 0;
3491}
3492
3493Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3494 return commonDivTransforms(I);
3495}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003496
Reid Spencer0a783f72006-11-02 01:53:59 +00003497/// This function implements the transforms on rem instructions that work
3498/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3499/// is used by the visitors to those instructions.
3500/// @brief Transforms common to all three rem instructions
3501Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003503
Chris Lattner50b2ca42008-02-19 06:12:18 +00003504 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3505 if (I.getType()->isFPOrFPVector())
3506 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003507 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003508 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003509 if (isa<UndefValue>(Op1))
3510 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003511
3512 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003513 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3514 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003515
Reid Spencer0a783f72006-11-02 01:53:59 +00003516 return 0;
3517}
3518
3519/// This function implements the transforms common to both integer remainder
3520/// instructions (urem and srem). It is called by the visitors to those integer
3521/// remainder instructions.
3522/// @brief Common integer remainder transforms
3523Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3525
3526 if (Instruction *common = commonRemTransforms(I))
3527 return common;
3528
Dale Johannesened6af242009-01-21 00:35:19 +00003529 // 0 % X == 0 for integer, we don't need to preserve faults!
3530 if (Constant *LHS = dyn_cast<Constant>(Op0))
3531 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003532 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003533
Chris Lattner857e8cd2004-12-12 21:48:58 +00003534 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003535 // X % 0 == undef, we don't need to preserve faults!
3536 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003537 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003538
Chris Lattnera2881962003-02-18 19:28:33 +00003539 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003540 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003541
Chris Lattner97943922006-02-28 05:49:21 +00003542 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3543 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3544 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3545 return R;
3546 } else if (isa<PHINode>(Op0I)) {
3547 if (Instruction *NV = FoldOpIntoPhi(I))
3548 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003549 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003550
3551 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003552 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003553 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003554 }
Chris Lattnera2881962003-02-18 19:28:33 +00003555 }
3556
Reid Spencer0a783f72006-11-02 01:53:59 +00003557 return 0;
3558}
3559
3560Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3562
3563 if (Instruction *common = commonIRemTransforms(I))
3564 return common;
3565
3566 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3567 // X urem C^2 -> X and C
3568 // Check to see if this is an unsigned remainder with an exact power of 2,
3569 // if so, convert to a bitwise and.
3570 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003571 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003572 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003573 }
3574
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003575 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003576 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3577 if (RHSI->getOpcode() == Instruction::Shl &&
3578 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003579 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003580 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003581 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003582 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003583 }
3584 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003585 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003586
Reid Spencer0a783f72006-11-02 01:53:59 +00003587 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3588 // where C1&C2 are powers of two.
3589 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3590 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3591 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3592 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003593 if ((STO->getValue().isPowerOf2()) &&
3594 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003595 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3596 SI->getName()+".t");
3597 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3598 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003599 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003600 }
3601 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003602 }
3603
Chris Lattner3f5b8772002-05-06 16:14:14 +00003604 return 0;
3605}
3606
Reid Spencer0a783f72006-11-02 01:53:59 +00003607Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3608 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3609
Dan Gohmancff55092007-11-05 23:16:33 +00003610 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003611 if (Instruction *Common = commonIRemTransforms(I))
3612 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003613
Dan Gohman186a6362009-08-12 16:04:34 +00003614 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003615 if (!isa<Constant>(RHSNeg) ||
3616 (isa<ConstantInt>(RHSNeg) &&
3617 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003618 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003619 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003620 I.setOperand(1, RHSNeg);
3621 return &I;
3622 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003623
Dan Gohmancff55092007-11-05 23:16:33 +00003624 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003625 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003626 if (I.getType()->isInteger()) {
3627 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3628 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3629 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003630 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003631 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003632 }
3633
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003634 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003635 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3636 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003637
Nick Lewycky9dce8732008-12-20 16:48:00 +00003638 bool hasNegative = false;
3639 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3640 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3641 if (RHS->getValue().isNegative())
3642 hasNegative = true;
3643
3644 if (hasNegative) {
3645 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003646 for (unsigned i = 0; i != VWidth; ++i) {
3647 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3648 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003649 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003650 else
3651 Elts[i] = RHS;
3652 }
3653 }
3654
Owen Andersonaf7ec972009-07-28 21:19:26 +00003655 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003656 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003657 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003658 I.setOperand(1, NewRHSV);
3659 return &I;
3660 }
3661 }
3662 }
3663
Reid Spencer0a783f72006-11-02 01:53:59 +00003664 return 0;
3665}
3666
3667Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003668 return commonRemTransforms(I);
3669}
3670
Chris Lattner457dd822004-06-09 07:59:58 +00003671// isOneBitSet - Return true if there is exactly one bit set in the specified
3672// constant.
3673static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003674 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003675}
3676
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003677// isHighOnes - Return true if the constant is of the form 1+0+.
3678// This is the same as lowones(~X).
3679static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003680 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003681}
3682
Reid Spencere4d87aa2006-12-23 06:05:41 +00003683/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003684/// are carefully arranged to allow folding of expressions such as:
3685///
3686/// (A < B) | (A > B) --> (A != B)
3687///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003688/// Note that this is only valid if the first and second predicates have the
3689/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003690///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003691/// Three bits are used to represent the condition, as follows:
3692/// 0 A > B
3693/// 1 A == B
3694/// 2 A < B
3695///
3696/// <=> Value Definition
3697/// 000 0 Always false
3698/// 001 1 A > B
3699/// 010 2 A == B
3700/// 011 3 A >= B
3701/// 100 4 A < B
3702/// 101 5 A != B
3703/// 110 6 A <= B
3704/// 111 7 Always true
3705///
3706static unsigned getICmpCode(const ICmpInst *ICI) {
3707 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003708 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 case ICmpInst::ICMP_UGT: return 1; // 001
3710 case ICmpInst::ICMP_SGT: return 1; // 001
3711 case ICmpInst::ICMP_EQ: return 2; // 010
3712 case ICmpInst::ICMP_UGE: return 3; // 011
3713 case ICmpInst::ICMP_SGE: return 3; // 011
3714 case ICmpInst::ICMP_ULT: return 4; // 100
3715 case ICmpInst::ICMP_SLT: return 4; // 100
3716 case ICmpInst::ICMP_NE: return 5; // 101
3717 case ICmpInst::ICMP_ULE: return 6; // 110
3718 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003719 // True -> 7
3720 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003721 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003722 return 0;
3723 }
3724}
3725
Evan Cheng8db90722008-10-14 17:15:11 +00003726/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3727/// predicate into a three bit mask. It also returns whether it is an ordered
3728/// predicate by reference.
3729static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3730 isOrdered = false;
3731 switch (CC) {
3732 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3733 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003734 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3735 case FCmpInst::FCMP_UGT: return 1; // 001
3736 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3737 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003738 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3739 case FCmpInst::FCMP_UGE: return 3; // 011
3740 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3741 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003742 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3743 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003744 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3745 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003746 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003747 default:
3748 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003749 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003750 return 0;
3751 }
3752}
3753
Reid Spencere4d87aa2006-12-23 06:05:41 +00003754/// getICmpValue - This is the complement of getICmpCode, which turns an
3755/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003756/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003757/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003758static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003759 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003761 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003762 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003763 case 1:
3764 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003765 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003766 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003767 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3768 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003769 case 3:
3770 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003771 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003772 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003773 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003774 case 4:
3775 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003776 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003777 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003778 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3779 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003780 case 6:
3781 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003782 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003783 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003784 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003785 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003786 }
3787}
3788
Evan Cheng8db90722008-10-14 17:15:11 +00003789/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3790/// opcode and two operands into either a FCmp instruction. isordered is passed
3791/// in to determine which kind of predicate to use in the new fcmp instruction.
3792static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003793 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003794 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003795 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003796 case 0:
3797 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003798 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003799 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003800 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003801 case 1:
3802 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003803 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003804 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003805 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003806 case 2:
3807 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003808 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003809 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003810 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003811 case 3:
3812 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003813 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003814 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003815 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003816 case 4:
3817 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003818 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003819 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003820 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003821 case 5:
3822 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003823 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003824 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003825 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003826 case 6:
3827 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003828 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003829 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003830 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003831 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003832 }
3833}
3834
Chris Lattnerb9553d62008-11-16 04:55:20 +00003835/// PredicatesFoldable - Return true if both predicates match sign or if at
3836/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003837static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003838 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3839 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3840 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003841}
3842
3843namespace {
3844// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3845struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003846 InstCombiner &IC;
3847 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003848 ICmpInst::Predicate pred;
3849 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3850 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3851 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003852 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003853 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3854 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003855 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3856 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003857 return false;
3858 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003859 Instruction *apply(Instruction &Log) const {
3860 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3861 if (ICI->getOperand(0) != LHS) {
3862 assert(ICI->getOperand(1) == LHS);
3863 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003864 }
3865
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003866 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003867 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003868 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003869 unsigned Code;
3870 switch (Log.getOpcode()) {
3871 case Instruction::And: Code = LHSCode & RHSCode; break;
3872 case Instruction::Or: Code = LHSCode | RHSCode; break;
3873 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003874 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003875 }
3876
Nick Lewycky4a134af2009-10-25 05:20:17 +00003877 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003878 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003879 if (Instruction *I = dyn_cast<Instruction>(RV))
3880 return I;
3881 // Otherwise, it's a constant boolean value...
3882 return IC.ReplaceInstUsesWith(Log, RV);
3883 }
3884};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003885} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003886
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003887// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3888// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003889// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003890Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003891 ConstantInt *OpRHS,
3892 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003893 BinaryOperator &TheAnd) {
3894 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003895 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003896 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003897 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003898
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003899 switch (Op->getOpcode()) {
3900 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003901 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003902 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003903 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003904 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003905 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003906 }
3907 break;
3908 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003909 if (Together == AndRHS) // (X | C) & C --> C
3910 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003911
Chris Lattner6e7ba452005-01-01 16:22:27 +00003912 if (Op->hasOneUse() && Together != OpRHS) {
3913 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003914 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003915 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003916 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003917 }
3918 break;
3919 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003920 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003921 // Adding a one to a single bit bit-field should be turned into an XOR
3922 // of the bit. First thing to check is to see if this AND is with a
3923 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003924 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003925
3926 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003927 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003928 // Ok, at this point, we know that we are masking the result of the
3929 // ADD down to exactly one bit. If the constant we are adding has
3930 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003931 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003932
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003933 // Check to see if any bits below the one bit set in AndRHSV are set.
3934 if ((AddRHS & (AndRHSV-1)) == 0) {
3935 // If not, the only thing that can effect the output of the AND is
3936 // the bit specified by AndRHSV. If that bit is set, the effect of
3937 // the XOR is to toggle the bit. If it is clear, then the ADD has
3938 // no effect.
3939 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3940 TheAnd.setOperand(0, X);
3941 return &TheAnd;
3942 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003943 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003944 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003945 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003946 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003947 }
3948 }
3949 }
3950 }
3951 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003952
3953 case Instruction::Shl: {
3954 // We know that the AND will not produce any of the bits shifted in, so if
3955 // the anded constant includes them, clear them now!
3956 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003957 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003958 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003959 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003960 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003961
Zhou Sheng290bec52007-03-29 08:15:12 +00003962 if (CI->getValue() == ShlMask) {
3963 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003964 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3965 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003966 TheAnd.setOperand(1, CI);
3967 return &TheAnd;
3968 }
3969 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003970 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003971 case Instruction::LShr:
3972 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003973 // We know that the AND will not produce any of the bits shifted in, so if
3974 // the anded constant includes them, clear them now! This only applies to
3975 // unsigned shifts, because a signed shr may bring in set bits!
3976 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003977 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003978 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003979 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003980 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003981
Zhou Sheng290bec52007-03-29 08:15:12 +00003982 if (CI->getValue() == ShrMask) {
3983 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003984 return ReplaceInstUsesWith(TheAnd, Op);
3985 } else if (CI != AndRHS) {
3986 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3987 return &TheAnd;
3988 }
3989 break;
3990 }
3991 case Instruction::AShr:
3992 // Signed shr.
3993 // See if this is shifting in some sign extension, then masking it out
3994 // with an and.
3995 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003996 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003997 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003998 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003999 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00004000 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00004001 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00004002 // Make the argument unsigned.
4003 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00004004 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004005 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00004006 }
Chris Lattner62a355c2003-09-19 19:05:02 +00004007 }
4008 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004009 }
4010 return 0;
4011}
4012
Chris Lattner8b170942002-08-09 23:47:40 +00004013
Chris Lattnera96879a2004-09-29 17:40:11 +00004014/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4015/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00004016/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4017/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00004018/// insert new instructions.
4019Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004020 bool isSigned, bool Inside,
4021 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004022 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00004023 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00004024 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004025
Chris Lattnera96879a2004-09-29 17:40:11 +00004026 if (Inside) {
4027 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004028 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00004029
Reid Spencere4d87aa2006-12-23 06:05:41 +00004030 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004031 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00004032 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00004033 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004034 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004035 }
4036
4037 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00004038 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00004039 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004040 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004041 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004042 }
4043
4044 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004045 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00004046
Reid Spencere4e40032007-03-21 23:19:50 +00004047 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00004048 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004049 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004050 ICmpInst::Predicate pred = (isSigned ?
4051 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004052 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004053 }
Reid Spencerb83eb642006-10-20 07:07:24 +00004054
Reid Spencere4e40032007-03-21 23:19:50 +00004055 // Emit V-Lo >u Hi-1-Lo
4056 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004057 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00004058 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004059 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004060 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004061}
4062
Chris Lattner7203e152005-09-18 07:22:02 +00004063// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4064// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4065// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4066// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004067static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004068 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004069 uint32_t BitWidth = Val->getType()->getBitWidth();
4070 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004071
4072 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004073 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004074 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004075 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004076 return true;
4077}
4078
Chris Lattner7203e152005-09-18 07:22:02 +00004079/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4080/// where isSub determines whether the operator is a sub. If we can fold one of
4081/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004082///
4083/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4084/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4085/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4086///
4087/// return (A +/- B).
4088///
4089Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004090 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004091 Instruction &I) {
4092 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4093 if (!LHSI || LHSI->getNumOperands() != 2 ||
4094 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4095
4096 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4097
4098 switch (LHSI->getOpcode()) {
4099 default: return 0;
4100 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004101 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004102 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004103 if ((Mask->getValue().countLeadingZeros() +
4104 Mask->getValue().countPopulation()) ==
4105 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004106 break;
4107
4108 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4109 // part, we don't need any explicit masks to take them out of A. If that
4110 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004111 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004112 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004113 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004114 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004115 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004116 break;
4117 }
4118 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004119 return 0;
4120 case Instruction::Or:
4121 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004122 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004123 if ((Mask->getValue().countLeadingZeros() +
4124 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004125 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004126 break;
4127 return 0;
4128 }
4129
Chris Lattnerc8e77562005-09-18 04:24:45 +00004130 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004131 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4132 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004133}
4134
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004135/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4136Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4137 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004138 // (icmp eq A, null) & (icmp eq B, null) -->
4139 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4140 if (TD &&
4141 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4142 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4143 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4144 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4145 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4146 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4147 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4148 Value *NewOr = Builder->CreateOr(A, B);
4149 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4150 Constant::getNullValue(IntPtrTy));
4151 }
4152
Chris Lattnerea065fb2008-11-16 05:10:52 +00004153 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004154 ConstantInt *LHSCst, *RHSCst;
4155 ICmpInst::Predicate LHSCC, RHSCC;
4156
Chris Lattnerea065fb2008-11-16 05:10:52 +00004157 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004158 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004159 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004160 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004161 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004162 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004163
Chris Lattner3f40e232009-11-29 00:51:17 +00004164 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4165 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4166 // where C is a power of 2
4167 if (LHSCC == ICmpInst::ICMP_ULT &&
4168 LHSCst->getValue().isPowerOf2()) {
4169 Value *NewOr = Builder->CreateOr(Val, Val2);
4170 return new ICmpInst(LHSCC, NewOr, LHSCst);
4171 }
4172
4173 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4174 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4175 Value *NewOr = Builder->CreateOr(Val, Val2);
4176 return new ICmpInst(LHSCC, NewOr, LHSCst);
4177 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004178 }
4179
4180 // From here on, we only handle:
4181 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4182 if (Val != Val2) return 0;
4183
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004184 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4185 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4186 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4187 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4188 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4189 return 0;
4190
4191 // We can't fold (ugt x, C) & (sgt x, C2).
4192 if (!PredicatesFoldable(LHSCC, RHSCC))
4193 return 0;
4194
4195 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004196 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004197 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004198 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004199 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004200 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004201 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004202 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4203
4204 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004205 std::swap(LHS, RHS);
4206 std::swap(LHSCst, RHSCst);
4207 std::swap(LHSCC, RHSCC);
4208 }
4209
4210 // At this point, we know we have have two icmp instructions
4211 // comparing a value against two constants and and'ing the result
4212 // together. Because of the above check, we know that we only have
4213 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4214 // (from the FoldICmpLogical check above), that the two constants
4215 // are not equal and that the larger constant is on the RHS
4216 assert(LHSCst != RHSCst && "Compares not folded above?");
4217
4218 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004219 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004220 case ICmpInst::ICMP_EQ:
4221 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004222 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004223 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4224 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4225 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004226 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004227 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4228 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4229 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4230 return ReplaceInstUsesWith(I, LHS);
4231 }
4232 case ICmpInst::ICMP_NE:
4233 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004234 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004235 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004236 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004237 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004238 break; // (X != 13 & X u< 15) -> no change
4239 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004240 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004241 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004242 break; // (X != 13 & X s< 15) -> no change
4243 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4244 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4245 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4246 return ReplaceInstUsesWith(I, RHS);
4247 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004248 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004249 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004250 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004251 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004252 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004253 }
4254 break; // (X != 13 & X != 15) -> no change
4255 }
4256 break;
4257 case ICmpInst::ICMP_ULT:
4258 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004259 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004260 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4261 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004262 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004263 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4264 break;
4265 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4266 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4267 return ReplaceInstUsesWith(I, LHS);
4268 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4269 break;
4270 }
4271 break;
4272 case ICmpInst::ICMP_SLT:
4273 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004274 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004275 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4276 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004277 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004278 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4279 break;
4280 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4281 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4282 return ReplaceInstUsesWith(I, LHS);
4283 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4284 break;
4285 }
4286 break;
4287 case ICmpInst::ICMP_UGT:
4288 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004289 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004290 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4291 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4292 return ReplaceInstUsesWith(I, RHS);
4293 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4294 break;
4295 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004296 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004297 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004298 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004299 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004300 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004301 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004302 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4303 break;
4304 }
4305 break;
4306 case ICmpInst::ICMP_SGT:
4307 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004308 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004309 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4310 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4311 return ReplaceInstUsesWith(I, RHS);
4312 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4313 break;
4314 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004315 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004316 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004317 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004318 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004319 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004320 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004321 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4322 break;
4323 }
4324 break;
4325 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004326
4327 return 0;
4328}
4329
Chris Lattner42d1be02009-07-23 05:14:02 +00004330Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4331 FCmpInst *RHS) {
4332
4333 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4334 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4335 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4336 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4337 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4338 // If either of the constants are nans, then the whole thing returns
4339 // false.
4340 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004341 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004342 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004343 LHS->getOperand(0), RHS->getOperand(0));
4344 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004345
4346 // Handle vector zeros. This occurs because the canonical form of
4347 // "fcmp ord x,x" is "fcmp ord x, 0".
4348 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4349 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004350 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004351 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004352 return 0;
4353 }
4354
4355 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4356 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4357 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4358
4359
4360 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4361 // Swap RHS operands to match LHS.
4362 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4363 std::swap(Op1LHS, Op1RHS);
4364 }
4365
4366 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4367 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4368 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004369 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004370
4371 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004372 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004373 if (Op0CC == FCmpInst::FCMP_TRUE)
4374 return ReplaceInstUsesWith(I, RHS);
4375 if (Op1CC == FCmpInst::FCMP_TRUE)
4376 return ReplaceInstUsesWith(I, LHS);
4377
4378 bool Op0Ordered;
4379 bool Op1Ordered;
4380 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4381 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4382 if (Op1Pred == 0) {
4383 std::swap(LHS, RHS);
4384 std::swap(Op0Pred, Op1Pred);
4385 std::swap(Op0Ordered, Op1Ordered);
4386 }
4387 if (Op0Pred == 0) {
4388 // uno && ueq -> uno && (uno || eq) -> ueq
4389 // ord && olt -> ord && (ord && lt) -> olt
4390 if (Op0Ordered == Op1Ordered)
4391 return ReplaceInstUsesWith(I, RHS);
4392
4393 // uno && oeq -> uno && (ord && eq) -> false
4394 // uno && ord -> false
4395 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004396 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004397 // ord && ueq -> ord && (uno || eq) -> oeq
4398 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4399 Op0LHS, Op0RHS, Context));
4400 }
4401 }
4402
4403 return 0;
4404}
4405
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004406
Chris Lattner7e708292002-06-25 16:13:24 +00004407Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004408 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004410
Chris Lattnerd06094f2009-11-10 00:55:12 +00004411 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4412 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004413
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004414 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004415 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004416 if (SimplifyDemandedInstructionBits(I))
4417 return &I;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004418
Dan Gohman6de29f82009-06-15 22:12:54 +00004419
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004420 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004421 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004422 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004423
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004424 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004425 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004426 Value *Op0LHS = Op0I->getOperand(0);
4427 Value *Op0RHS = Op0I->getOperand(1);
4428 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004429 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004430 case Instruction::Xor:
4431 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004432 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004433 if (!Op0I->hasOneUse()) break;
4434
4435 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4436 // Not masking anything out for the LHS, move to RHS.
4437 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4438 Op0RHS->getName()+".masked");
4439 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4440 }
4441 if (!isa<Constant>(Op0RHS) &&
4442 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4443 // Not masking anything out for the RHS, move to LHS.
4444 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4445 Op0LHS->getName()+".masked");
4446 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004447 }
4448
Chris Lattner6e7ba452005-01-01 16:22:27 +00004449 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004450 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004451 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4452 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4453 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4454 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004455 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004456 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004457 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004458 break;
4459
4460 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004461 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4462 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4463 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4464 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004465 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004466
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004467 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4468 // has 1's for all bits that the subtraction with A might affect.
4469 if (Op0I->hasOneUse()) {
4470 uint32_t BitWidth = AndRHSMask.getBitWidth();
4471 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4472 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4473
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004474 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004475 if (!(A && A->isZero()) && // avoid infinite recursion.
4476 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004477 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004478 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4479 }
4480 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004481 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004482
4483 case Instruction::Shl:
4484 case Instruction::LShr:
4485 // (1 << x) & 1 --> zext(x == 0)
4486 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004487 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004488 Value *NewICmp =
4489 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004490 return new ZExtInst(NewICmp, I.getType());
4491 }
4492 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004493 }
4494
Chris Lattner58403262003-07-23 19:25:52 +00004495 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004496 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004497 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004498 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004499 // If this is an integer truncation or change from signed-to-unsigned, and
4500 // if the source is an and/or with immediate, transform it. This
4501 // frequently occurs for bitfield accesses.
4502 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004503 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004504 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004505 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004506 if (CastOp->getOpcode() == Instruction::And) {
4507 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004508 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4509 // This will fold the two constants together, which may allow
4510 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004511 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004512 CastOp->getOperand(0), I.getType(),
4513 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004514 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004515 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004516 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004517 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004518 } else if (CastOp->getOpcode() == Instruction::Or) {
4519 // Change: and (cast (or X, C1) to T), C2
4520 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004521 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004522 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004523 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004524 return ReplaceInstUsesWith(I, AndRHS);
4525 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004526 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004527 }
Chris Lattner06782f82003-07-23 19:36:21 +00004528 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004529
4530 // Try to fold constant and into select arguments.
4531 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004532 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004533 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004534 if (isa<PHINode>(Op0))
4535 if (Instruction *NV = FoldOpIntoPhi(I))
4536 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004537 }
4538
Chris Lattner5b62aa72004-06-18 06:07:51 +00004539
Misha Brukmancb6267b2004-07-30 12:50:08 +00004540 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004541 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4542 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4543 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4544 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4545 I.getName()+".demorgan");
4546 return BinaryOperator::CreateNot(Or);
4547 }
4548
Chris Lattner2082ad92006-02-13 23:07:23 +00004549 {
Chris Lattner003b6202007-06-15 05:58:24 +00004550 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004551 // (A|B) & ~(A&B) -> A^B
4552 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4553 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4554 ((A == C && B == D) || (A == D && B == C)))
4555 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004556
Chris Lattnerd06094f2009-11-10 00:55:12 +00004557 // ~(A&B) & (A|B) -> A^B
4558 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4559 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4560 ((A == C && B == D) || (A == D && B == C)))
4561 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004562
4563 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004564 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004565 if (A == Op1) { // (A^B)&A -> A&(A^B)
4566 I.swapOperands(); // Simplify below
4567 std::swap(Op0, Op1);
4568 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4569 cast<BinaryOperator>(Op0)->swapOperands();
4570 I.swapOperands(); // Simplify below
4571 std::swap(Op0, Op1);
4572 }
4573 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004574
Chris Lattner64daab52006-04-01 08:03:55 +00004575 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004576 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004577 if (B == Op0) { // B&(A^B) -> B&(B^A)
4578 cast<BinaryOperator>(Op1)->swapOperands();
4579 std::swap(A, B);
4580 }
Chris Lattner74381062009-08-30 07:44:24 +00004581 if (A == Op0) // A&(A^B) -> A & ~B
4582 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004583 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004584
4585 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004586 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4587 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004588 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004589 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4590 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004591 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004592 }
4593
Reid Spencere4d87aa2006-12-23 06:05:41 +00004594 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4595 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004596 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004597 return R;
4598
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004599 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4600 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4601 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004602 }
4603
Chris Lattner6fc205f2006-05-05 06:39:07 +00004604 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004605 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4606 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4607 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4608 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004609 if (SrcTy == Op1C->getOperand(0)->getType() &&
4610 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004611 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004612 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4613 I.getType(), TD) &&
4614 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4615 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004616 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4617 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004618 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004619 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004620 }
Chris Lattnere511b742006-11-14 07:46:50 +00004621
4622 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004623 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4624 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4625 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004626 SI0->getOperand(1) == SI1->getOperand(1) &&
4627 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004628 Value *NewOp =
4629 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4630 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004631 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004632 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004633 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004634 }
4635
Evan Cheng8db90722008-10-14 17:15:11 +00004636 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004637 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004638 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4639 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4640 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004641 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004642
Chris Lattner7e708292002-06-25 16:13:24 +00004643 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004644}
4645
Chris Lattner8c34cd22008-10-05 02:13:19 +00004646/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4647/// capable of providing pieces of a bswap. The subexpression provides pieces
4648/// of a bswap if it is proven that each of the non-zero bytes in the output of
4649/// the expression came from the corresponding "byte swapped" byte in some other
4650/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4651/// we know that the expression deposits the low byte of %X into the high byte
4652/// of the bswap result and that all other bytes are zero. This expression is
4653/// accepted, the high byte of ByteValues is set to X to indicate a correct
4654/// match.
4655///
4656/// This function returns true if the match was unsuccessful and false if so.
4657/// On entry to the function the "OverallLeftShift" is a signed integer value
4658/// indicating the number of bytes that the subexpression is later shifted. For
4659/// example, if the expression is later right shifted by 16 bits, the
4660/// OverallLeftShift value would be -2 on entry. This is used to specify which
4661/// byte of ByteValues is actually being set.
4662///
4663/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4664/// byte is masked to zero by a user. For example, in (X & 255), X will be
4665/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4666/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4667/// always in the local (OverallLeftShift) coordinate space.
4668///
4669static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4670 SmallVector<Value*, 8> &ByteValues) {
4671 if (Instruction *I = dyn_cast<Instruction>(V)) {
4672 // If this is an or instruction, it may be an inner node of the bswap.
4673 if (I->getOpcode() == Instruction::Or) {
4674 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4675 ByteValues) ||
4676 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4677 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004678 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004679
4680 // If this is a logical shift by a constant multiple of 8, recurse with
4681 // OverallLeftShift and ByteMask adjusted.
4682 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4683 unsigned ShAmt =
4684 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4685 // Ensure the shift amount is defined and of a byte value.
4686 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4687 return true;
4688
4689 unsigned ByteShift = ShAmt >> 3;
4690 if (I->getOpcode() == Instruction::Shl) {
4691 // X << 2 -> collect(X, +2)
4692 OverallLeftShift += ByteShift;
4693 ByteMask >>= ByteShift;
4694 } else {
4695 // X >>u 2 -> collect(X, -2)
4696 OverallLeftShift -= ByteShift;
4697 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004698 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004699 }
4700
4701 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4702 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4703
4704 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4705 ByteValues);
4706 }
4707
4708 // If this is a logical 'and' with a mask that clears bytes, clear the
4709 // corresponding bytes in ByteMask.
4710 if (I->getOpcode() == Instruction::And &&
4711 isa<ConstantInt>(I->getOperand(1))) {
4712 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4713 unsigned NumBytes = ByteValues.size();
4714 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4715 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4716
4717 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4718 // If this byte is masked out by a later operation, we don't care what
4719 // the and mask is.
4720 if ((ByteMask & (1 << i)) == 0)
4721 continue;
4722
4723 // If the AndMask is all zeros for this byte, clear the bit.
4724 APInt MaskB = AndMask & Byte;
4725 if (MaskB == 0) {
4726 ByteMask &= ~(1U << i);
4727 continue;
4728 }
4729
4730 // If the AndMask is not all ones for this byte, it's not a bytezap.
4731 if (MaskB != Byte)
4732 return true;
4733
4734 // Otherwise, this byte is kept.
4735 }
4736
4737 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4738 ByteValues);
4739 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004740 }
4741
Chris Lattner8c34cd22008-10-05 02:13:19 +00004742 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4743 // the input value to the bswap. Some observations: 1) if more than one byte
4744 // is demanded from this input, then it could not be successfully assembled
4745 // into a byteswap. At least one of the two bytes would not be aligned with
4746 // their ultimate destination.
4747 if (!isPowerOf2_32(ByteMask)) return true;
4748 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004749
Chris Lattner8c34cd22008-10-05 02:13:19 +00004750 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4751 // is demanded, it needs to go into byte 0 of the result. This means that the
4752 // byte needs to be shifted until it lands in the right byte bucket. The
4753 // shift amount depends on the position: if the byte is coming from the high
4754 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4755 // low part, it must be shifted left.
4756 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4757 if (InputByteNo < ByteValues.size()/2) {
4758 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4759 return true;
4760 } else {
4761 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4762 return true;
4763 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004764
4765 // If the destination byte value is already defined, the values are or'd
4766 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004767 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004768 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004769 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004770 return false;
4771}
4772
4773/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4774/// If so, insert the new bswap intrinsic and return it.
4775Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004776 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004777 if (!ITy || ITy->getBitWidth() % 16 ||
4778 // ByteMask only allows up to 32-byte values.
4779 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004780 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004781
4782 /// ByteValues - For each byte of the result, we keep track of which value
4783 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004784 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004785 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004786
4787 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004788 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4789 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004790 return 0;
4791
4792 // Check to see if all of the bytes come from the same value.
4793 Value *V = ByteValues[0];
4794 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4795
4796 // Check to make sure that all of the bytes come from the same value.
4797 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4798 if (ByteValues[i] != V)
4799 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004800 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004801 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004802 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004803 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004804}
4805
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004806/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4807/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4808/// we can simplify this expression to "cond ? C : D or B".
4809static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004810 Value *C, Value *D,
4811 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004812 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004813 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004814 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004815 return 0;
4816
Chris Lattnera6a474d2008-11-16 04:26:55 +00004817 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004818 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004819 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004820 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004821 return SelectInst::Create(Cond, C, B);
4822 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004823 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004824 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004825 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004826 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004827 return 0;
4828}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004829
Chris Lattner69d4ced2008-11-16 05:20:07 +00004830/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4831Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4832 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004833 // (icmp ne A, null) | (icmp ne B, null) -->
4834 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4835 if (TD &&
4836 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4837 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4838 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4839 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4840 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4841 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4842 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4843 Value *NewOr = Builder->CreateOr(A, B);
4844 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4845 Constant::getNullValue(IntPtrTy));
4846 }
4847
Chris Lattner69d4ced2008-11-16 05:20:07 +00004848 Value *Val, *Val2;
4849 ConstantInt *LHSCst, *RHSCst;
4850 ICmpInst::Predicate LHSCC, RHSCC;
4851
4852 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004853 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4854 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004855 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004856
4857
4858 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4859 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4860 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4861 Value *NewOr = Builder->CreateOr(Val, Val2);
4862 return new ICmpInst(LHSCC, NewOr, LHSCst);
4863 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004864
4865 // From here on, we only handle:
4866 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4867 if (Val != Val2) return 0;
4868
4869 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4870 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4871 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4872 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4873 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4874 return 0;
4875
4876 // We can't fold (ugt x, C) | (sgt x, C2).
4877 if (!PredicatesFoldable(LHSCC, RHSCC))
4878 return 0;
4879
4880 // Ensure that the larger constant is on the RHS.
4881 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004882 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004883 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004884 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004885 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4886 else
4887 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4888
4889 if (ShouldSwap) {
4890 std::swap(LHS, RHS);
4891 std::swap(LHSCst, RHSCst);
4892 std::swap(LHSCC, RHSCC);
4893 }
4894
4895 // At this point, we know we have have two icmp instructions
4896 // comparing a value against two constants and or'ing the result
4897 // together. Because of the above check, we know that we only have
4898 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4899 // FoldICmpLogical check above), that the two constants are not
4900 // equal.
4901 assert(LHSCst != RHSCst && "Compares not folded above?");
4902
4903 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004904 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004905 case ICmpInst::ICMP_EQ:
4906 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004908 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004909 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004910 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004911 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004912 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004913 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004914 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004915 }
4916 break; // (X == 13 | X == 15) -> no change
4917 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4918 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4919 break;
4920 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4921 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4922 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4923 return ReplaceInstUsesWith(I, RHS);
4924 }
4925 break;
4926 case ICmpInst::ICMP_NE:
4927 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004928 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004929 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4930 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4931 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4932 return ReplaceInstUsesWith(I, LHS);
4933 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4934 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4935 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004936 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004937 }
4938 break;
4939 case ICmpInst::ICMP_ULT:
4940 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004941 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004942 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4943 break;
4944 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4945 // If RHSCst is [us]MAXINT, it is always false. Not handling
4946 // this can cause overflow.
4947 if (RHSCst->isMaxValue(false))
4948 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004949 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004950 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004951 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4952 break;
4953 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4954 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4955 return ReplaceInstUsesWith(I, RHS);
4956 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4957 break;
4958 }
4959 break;
4960 case ICmpInst::ICMP_SLT:
4961 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004962 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004963 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4964 break;
4965 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4966 // If RHSCst is [us]MAXINT, it is always false. Not handling
4967 // this can cause overflow.
4968 if (RHSCst->isMaxValue(true))
4969 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004970 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004971 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004972 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4973 break;
4974 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4975 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4976 return ReplaceInstUsesWith(I, RHS);
4977 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4978 break;
4979 }
4980 break;
4981 case ICmpInst::ICMP_UGT:
4982 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004983 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004984 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4985 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4986 return ReplaceInstUsesWith(I, LHS);
4987 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4988 break;
4989 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4990 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004991 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004992 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4993 break;
4994 }
4995 break;
4996 case ICmpInst::ICMP_SGT:
4997 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004998 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004999 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
5000 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
5001 return ReplaceInstUsesWith(I, LHS);
5002 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
5003 break;
5004 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5005 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005006 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00005007 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5008 break;
5009 }
5010 break;
5011 }
5012 return 0;
5013}
5014
Chris Lattner5414cc52009-07-23 05:46:22 +00005015Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5016 FCmpInst *RHS) {
5017 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5018 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5019 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5020 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5021 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5022 // If either of the constants are nans, then the whole thing returns
5023 // true.
5024 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00005025 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005026
5027 // Otherwise, no need to compare the two constants, compare the
5028 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005029 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005030 LHS->getOperand(0), RHS->getOperand(0));
5031 }
5032
5033 // Handle vector zeros. This occurs because the canonical form of
5034 // "fcmp uno x,x" is "fcmp uno x, 0".
5035 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5036 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005037 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005038 LHS->getOperand(0), RHS->getOperand(0));
5039
5040 return 0;
5041 }
5042
5043 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5044 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5045 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5046
5047 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5048 // Swap RHS operands to match LHS.
5049 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5050 std::swap(Op1LHS, Op1RHS);
5051 }
5052 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5053 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5054 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005055 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00005056 Op0LHS, Op0RHS);
5057 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005058 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005059 if (Op0CC == FCmpInst::FCMP_FALSE)
5060 return ReplaceInstUsesWith(I, RHS);
5061 if (Op1CC == FCmpInst::FCMP_FALSE)
5062 return ReplaceInstUsesWith(I, LHS);
5063 bool Op0Ordered;
5064 bool Op1Ordered;
5065 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5066 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5067 if (Op0Ordered == Op1Ordered) {
5068 // If both are ordered or unordered, return a new fcmp with
5069 // or'ed predicates.
5070 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5071 Op0LHS, Op0RHS, Context);
5072 if (Instruction *I = dyn_cast<Instruction>(RV))
5073 return I;
5074 // Otherwise, it's a constant boolean value...
5075 return ReplaceInstUsesWith(I, RV);
5076 }
5077 }
5078 return 0;
5079}
5080
Bill Wendlinga698a472008-12-01 08:23:25 +00005081/// FoldOrWithConstants - This helper function folds:
5082///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005083/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005084///
5085/// into:
5086///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005087/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005088///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005089/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005090Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005091 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005092 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5093 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005094
Bill Wendling286a0542008-12-02 06:24:20 +00005095 Value *V1 = 0;
5096 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005097 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005098
Bill Wendling29976b92008-12-02 06:18:11 +00005099 APInt Xor = CI1->getValue() ^ CI2->getValue();
5100 if (!Xor.isAllOnesValue()) return 0;
5101
Bill Wendling286a0542008-12-02 06:24:20 +00005102 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005103 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005104 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005105 }
5106
5107 return 0;
5108}
5109
Chris Lattner7e708292002-06-25 16:13:24 +00005110Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005111 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005113
Chris Lattnerd06094f2009-11-10 00:55:12 +00005114 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5115 return ReplaceInstUsesWith(I, V);
5116
5117
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005118 // See if we can simplify any instructions used by the instruction whose sole
5119 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005120 if (SimplifyDemandedInstructionBits(I))
5121 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005122
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005123 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005124 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005125 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005126 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005127 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005128 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005129 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005130 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005131 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005132 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005133
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005134 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005135 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005136 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005137 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005138 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005139 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005140 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005141 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005142
5143 // Try to fold constant and into select arguments.
5144 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005145 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005146 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005147 if (isa<PHINode>(Op0))
5148 if (Instruction *NV = FoldOpIntoPhi(I))
5149 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005150 }
5151
Chris Lattner4f637d42006-01-06 17:59:59 +00005152 Value *A = 0, *B = 0;
5153 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005154
Chris Lattner6423d4c2006-07-10 20:25:24 +00005155 // (A | B) | C and A | (B | C) -> bswap if possible.
5156 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005157 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5158 match(Op1, m_Or(m_Value(), m_Value())) ||
5159 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5160 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005161 if (Instruction *BSwap = MatchBSwap(I))
5162 return BSwap;
5163 }
5164
Chris Lattner6e4c6492005-05-09 04:58:36 +00005165 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005166 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005167 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005168 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005169 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005170 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005171 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005172 }
5173
5174 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005175 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005176 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005177 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005178 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005179 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005180 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005181 }
5182
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005183 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005184 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005185 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5186 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005187 Value *V1 = 0, *V2 = 0, *V3 = 0;
5188 C1 = dyn_cast<ConstantInt>(C);
5189 C2 = dyn_cast<ConstantInt>(D);
5190 if (C1 && C2) { // (A & C1)|(B & C2)
5191 // If we have: ((V + N) & C1) | (V & C2)
5192 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5193 // replace with V+N.
5194 if (C1->getValue() == ~C2->getValue()) {
5195 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005196 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005197 // Add commutes, try both ways.
5198 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5199 return ReplaceInstUsesWith(I, A);
5200 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5201 return ReplaceInstUsesWith(I, A);
5202 }
5203 // Or commutes, try both ways.
5204 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005205 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005206 // Add commutes, try both ways.
5207 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5208 return ReplaceInstUsesWith(I, B);
5209 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5210 return ReplaceInstUsesWith(I, B);
5211 }
5212 }
Chris Lattner044e5332007-04-08 08:01:49 +00005213 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005214 }
5215
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005216 // Check to see if we have any common things being and'ed. If so, find the
5217 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005218 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5219 if (A == B) // (A & C)|(A & D) == A & (C|D)
5220 V1 = A, V2 = C, V3 = D;
5221 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5222 V1 = A, V2 = B, V3 = C;
5223 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5224 V1 = C, V2 = A, V3 = D;
5225 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5226 V1 = C, V2 = A, V3 = B;
5227
5228 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005229 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005230 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005231 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005232 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005233
Dan Gohman1975d032008-10-30 20:40:10 +00005234 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005235 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005236 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005237 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005238 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005239 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005240 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005241 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005242 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005243
Bill Wendlingb01865c2008-11-30 13:52:49 +00005244 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005245 if ((match(C, m_Not(m_Specific(D))) &&
5246 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005247 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005248 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005249 if ((match(A, m_Not(m_Specific(D))) &&
5250 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005251 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005252 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005253 if ((match(C, m_Not(m_Specific(B))) &&
5254 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005255 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005256 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005257 if ((match(A, m_Not(m_Specific(B))) &&
5258 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005259 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005260 }
Chris Lattnere511b742006-11-14 07:46:50 +00005261
5262 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005263 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5264 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5265 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005266 SI0->getOperand(1) == SI1->getOperand(1) &&
5267 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005268 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5269 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005270 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005271 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005272 }
5273 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005274
Bill Wendlingb3833d12008-12-01 01:07:11 +00005275 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005276 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5277 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005278 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005279 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005280 }
5281 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005282 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5283 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005284 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005285 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005286 }
5287
Chris Lattnerd06094f2009-11-10 00:55:12 +00005288 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5289 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5290 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5291 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5292 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5293 I.getName()+".demorgan");
5294 return BinaryOperator::CreateNot(And);
5295 }
Chris Lattnera2881962003-02-18 19:28:33 +00005296
Reid Spencere4d87aa2006-12-23 06:05:41 +00005297 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5298 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005299 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005300 return R;
5301
Chris Lattner69d4ced2008-11-16 05:20:07 +00005302 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5303 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5304 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005305 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005306
5307 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005308 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005309 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005310 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005311 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5312 !isa<ICmpInst>(Op1C->getOperand(0))) {
5313 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005314 if (SrcTy == Op1C->getOperand(0)->getType() &&
5315 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005316 // Only do this if the casts both really cause code to be
5317 // generated.
5318 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5319 I.getType(), TD) &&
5320 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5321 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005322 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5323 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005324 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005325 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005326 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005327 }
Chris Lattner99c65742007-10-24 05:38:08 +00005328 }
5329
5330
5331 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5332 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005333 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5334 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5335 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005336 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005337
Chris Lattner7e708292002-06-25 16:13:24 +00005338 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005339}
5340
Dan Gohman844731a2008-05-13 00:00:25 +00005341namespace {
5342
Chris Lattnerc317d392004-02-16 01:20:27 +00005343// XorSelf - Implements: X ^ X --> 0
5344struct XorSelf {
5345 Value *RHS;
5346 XorSelf(Value *rhs) : RHS(rhs) {}
5347 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5348 Instruction *apply(BinaryOperator &Xor) const {
5349 return &Xor;
5350 }
5351};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005352
Dan Gohman844731a2008-05-13 00:00:25 +00005353}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005354
Chris Lattner7e708292002-06-25 16:13:24 +00005355Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005356 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005357 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005358
Evan Chengd34af782008-03-25 20:07:13 +00005359 if (isa<UndefValue>(Op1)) {
5360 if (isa<UndefValue>(Op0))
5361 // Handle undef ^ undef -> 0 special case. This is a common
5362 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005363 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005364 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005365 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005366
Chris Lattnerc317d392004-02-16 01:20:27 +00005367 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005368 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005369 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005371 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005372
5373 // See if we can simplify any instructions used by the instruction whose sole
5374 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005375 if (SimplifyDemandedInstructionBits(I))
5376 return &I;
5377 if (isa<VectorType>(I.getType()))
5378 if (isa<ConstantAggregateZero>(Op1))
5379 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005380
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005381 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005382 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005383 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5384 if (Op0I->getOpcode() == Instruction::And ||
5385 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005386 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5387 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5388 if (dyn_castNotVal(Op0I->getOperand(1)))
5389 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005390 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005391 Value *NotY =
5392 Builder->CreateNot(Op0I->getOperand(1),
5393 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005394 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005395 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005396 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005397 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005398
5399 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5400 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5401 if (isFreeToInvert(Op0I->getOperand(0)) &&
5402 isFreeToInvert(Op0I->getOperand(1))) {
5403 Value *NotX =
5404 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5405 Value *NotY =
5406 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5407 if (Op0I->getOpcode() == Instruction::And)
5408 return BinaryOperator::CreateOr(NotX, NotY);
5409 return BinaryOperator::CreateAnd(NotX, NotY);
5410 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005411 }
5412 }
5413 }
5414
5415
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005416 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005417 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005418 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005419 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005420 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005421 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005422
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005423 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005424 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005425 FCI->getOperand(0), FCI->getOperand(1));
5426 }
5427
Nick Lewycky517e1f52008-05-31 19:01:33 +00005428 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5429 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5430 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5431 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5432 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005433 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5434 (RHS == ConstantExpr::getCast(Opcode,
5435 ConstantInt::getTrue(*Context),
5436 Op0C->getDestTy()))) {
5437 CI->setPredicate(CI->getInversePredicate());
5438 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005439 }
5440 }
5441 }
5442 }
5443
Reid Spencere4d87aa2006-12-23 06:05:41 +00005444 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005445 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005446 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5447 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005448 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5449 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005450 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005451 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005452 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005453
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005454 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005455 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005456 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005457 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005458 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005459 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005460 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005461 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005462 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005463 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005464 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005465 Constant *C = ConstantInt::get(*Context,
5466 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005467 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005468
Chris Lattner7c4049c2004-01-12 19:35:11 +00005469 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005470 } else if (Op0I->getOpcode() == Instruction::Or) {
5471 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005472 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005473 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005474 // Anything in both C1 and C2 is known to be zero, remove it from
5475 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005476 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5477 NewRHS = ConstantExpr::getAnd(NewRHS,
5478 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005479 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005480 I.setOperand(0, Op0I->getOperand(0));
5481 I.setOperand(1, NewRHS);
5482 return &I;
5483 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005484 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005485 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005486 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005487
5488 // Try to fold constant and into select arguments.
5489 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005490 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005491 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005492 if (isa<PHINode>(Op0))
5493 if (Instruction *NV = FoldOpIntoPhi(I))
5494 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005495 }
5496
Dan Gohman186a6362009-08-12 16:04:34 +00005497 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005498 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005499 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005500
Dan Gohman186a6362009-08-12 16:04:34 +00005501 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005502 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005503 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005504
Chris Lattner318bf792007-03-18 22:51:34 +00005505
5506 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5507 if (Op1I) {
5508 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005509 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005510 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005511 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005512 I.swapOperands();
5513 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005514 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005515 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005516 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005517 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005518 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005519 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005520 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005521 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005522 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005523 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005524 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005525 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005526 std::swap(A, B);
5527 }
Chris Lattner318bf792007-03-18 22:51:34 +00005528 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005529 I.swapOperands(); // Simplified below.
5530 std::swap(Op0, Op1);
5531 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005532 }
Chris Lattner318bf792007-03-18 22:51:34 +00005533 }
5534
5535 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5536 if (Op0I) {
5537 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005538 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005539 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005540 if (A == Op1) // (B|A)^B == (A|B)^B
5541 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005542 if (B == Op1) // (A|B)^B == A & ~B
5543 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005544 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005545 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005546 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005547 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005548 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005549 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005550 if (A == Op1) // (A&B)^A -> (B&A)^A
5551 std::swap(A, B);
5552 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005553 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005554 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005555 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005556 }
Chris Lattner318bf792007-03-18 22:51:34 +00005557 }
5558
5559 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5560 if (Op0I && Op1I && Op0I->isShift() &&
5561 Op0I->getOpcode() == Op1I->getOpcode() &&
5562 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5563 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005564 Value *NewOp =
5565 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5566 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005567 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005568 Op1I->getOperand(1));
5569 }
5570
5571 if (Op0I && Op1I) {
5572 Value *A, *B, *C, *D;
5573 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005574 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5575 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005576 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005577 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005578 }
5579 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005580 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5581 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005582 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005583 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005584 }
5585
5586 // (A & B)^(C & D)
5587 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005588 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5589 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005590 // (X & Y)^(X & Y) -> (Y^Z) & X
5591 Value *X = 0, *Y = 0, *Z = 0;
5592 if (A == C)
5593 X = A, Y = B, Z = D;
5594 else if (A == D)
5595 X = A, Y = B, Z = C;
5596 else if (B == C)
5597 X = B, Y = A, Z = D;
5598 else if (B == D)
5599 X = B, Y = A, Z = C;
5600
5601 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005602 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005603 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005604 }
5605 }
5606 }
5607
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5609 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005610 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005611 return R;
5612
Chris Lattner6fc205f2006-05-05 06:39:07 +00005613 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005614 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005615 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005616 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5617 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005618 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005619 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005620 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5621 I.getType(), TD) &&
5622 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5623 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005624 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5625 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005626 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005627 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005628 }
Chris Lattner99c65742007-10-24 05:38:08 +00005629 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005630
Chris Lattner7e708292002-06-25 16:13:24 +00005631 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005632}
5633
Owen Andersond672ecb2009-07-03 00:17:18 +00005634static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005635 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005636 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005637}
Chris Lattnera96879a2004-09-29 17:40:11 +00005638
Dan Gohman6de29f82009-06-15 22:12:54 +00005639static bool HasAddOverflow(ConstantInt *Result,
5640 ConstantInt *In1, ConstantInt *In2,
5641 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005642 if (IsSigned)
5643 if (In2->getValue().isNegative())
5644 return Result->getValue().sgt(In1->getValue());
5645 else
5646 return Result->getValue().slt(In1->getValue());
5647 else
5648 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005649}
5650
Dan Gohman6de29f82009-06-15 22:12:54 +00005651/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005652/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005653static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005654 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005655 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005656 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005657
Dan Gohman6de29f82009-06-15 22:12:54 +00005658 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5659 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005660 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005661 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5662 ExtractElement(In1, Idx, Context),
5663 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005664 IsSigned))
5665 return true;
5666 }
5667 return false;
5668 }
5669
5670 return HasAddOverflow(cast<ConstantInt>(Result),
5671 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5672 IsSigned);
5673}
5674
5675static bool HasSubOverflow(ConstantInt *Result,
5676 ConstantInt *In1, ConstantInt *In2,
5677 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005678 if (IsSigned)
5679 if (In2->getValue().isNegative())
5680 return Result->getValue().slt(In1->getValue());
5681 else
5682 return Result->getValue().sgt(In1->getValue());
5683 else
5684 return Result->getValue().ugt(In1->getValue());
5685}
5686
Dan Gohman6de29f82009-06-15 22:12:54 +00005687/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5688/// overflowed for this type.
5689static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005690 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005691 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005692 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005693
5694 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5695 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005696 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005697 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5698 ExtractElement(In1, Idx, Context),
5699 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005700 IsSigned))
5701 return true;
5702 }
5703 return false;
5704 }
5705
5706 return HasSubOverflow(cast<ConstantInt>(Result),
5707 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5708 IsSigned);
5709}
5710
Chris Lattner10c0d912008-04-22 02:53:33 +00005711
Reid Spencere4d87aa2006-12-23 06:05:41 +00005712/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005713/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005714Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005715 ICmpInst::Predicate Cond,
5716 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005717 // Look through bitcasts.
5718 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5719 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005720
Chris Lattner574da9b2005-01-13 20:14:25 +00005721 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005722 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005723 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005724 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005725 // know pointers can't overflow since the gep is inbounds. See if we can
5726 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005727 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5728
5729 // If not, synthesize the offset the hard way.
5730 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005731 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005732 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005733 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005734 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005735 // If the base pointers are different, but the indices are the same, just
5736 // compare the base pointer.
5737 if (PtrBase != GEPRHS->getOperand(0)) {
5738 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005739 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005740 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005741 if (IndicesTheSame)
5742 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5743 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5744 IndicesTheSame = false;
5745 break;
5746 }
5747
5748 // If all indices are the same, just compare the base pointers.
5749 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005750 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005751 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005752
5753 // Otherwise, the base pointers are different and the indices are
5754 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005755 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005756 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005757
Chris Lattnere9d782b2005-01-13 22:25:21 +00005758 // If one of the GEPs has all zero indices, recurse.
5759 bool AllZeros = true;
5760 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5761 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5762 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5763 AllZeros = false;
5764 break;
5765 }
5766 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005767 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5768 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005769
5770 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005771 AllZeros = true;
5772 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5773 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5774 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5775 AllZeros = false;
5776 break;
5777 }
5778 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005779 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005780
Chris Lattner4401c9c2005-01-14 00:20:05 +00005781 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5782 // If the GEPs only differ by one index, compare it.
5783 unsigned NumDifferences = 0; // Keep track of # differences.
5784 unsigned DiffOperand = 0; // The operand that differs.
5785 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5786 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005787 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5788 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005789 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005790 NumDifferences = 2;
5791 break;
5792 } else {
5793 if (NumDifferences++) break;
5794 DiffOperand = i;
5795 }
5796 }
5797
5798 if (NumDifferences == 0) // SAME GEP?
5799 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005800 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005801 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005802
Chris Lattner4401c9c2005-01-14 00:20:05 +00005803 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005804 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5805 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005806 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005807 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005808 }
5809 }
5810
Reid Spencere4d87aa2006-12-23 06:05:41 +00005811 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005812 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005813 if (TD &&
5814 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005815 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5816 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005817 Value *L = EmitGEPOffset(GEPLHS, *this);
5818 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005819 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005820 }
5821 }
5822 return 0;
5823}
5824
Chris Lattnera5406232008-05-19 20:18:56 +00005825/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5826///
5827Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5828 Instruction *LHSI,
5829 Constant *RHSC) {
5830 if (!isa<ConstantFP>(RHSC)) return 0;
5831 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5832
5833 // Get the width of the mantissa. We don't want to hack on conversions that
5834 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005835 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005836 if (MantissaWidth == -1) return 0; // Unknown.
5837
5838 // Check to see that the input is converted from an integer type that is small
5839 // enough that preserves all bits. TODO: check here for "known" sign bits.
5840 // 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 +00005841 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005842
5843 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005844 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5845 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005846 ++InputSize;
5847
5848 // If the conversion would lose info, don't hack on this.
5849 if ((int)InputSize > MantissaWidth)
5850 return 0;
5851
5852 // Otherwise, we can potentially simplify the comparison. We know that it
5853 // will always come through as an integer value and we know the constant is
5854 // not a NAN (it would have been previously simplified).
5855 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5856
5857 ICmpInst::Predicate Pred;
5858 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005859 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005860 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005861 case FCmpInst::FCMP_OEQ:
5862 Pred = ICmpInst::ICMP_EQ;
5863 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005864 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005865 case FCmpInst::FCMP_OGT:
5866 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5867 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005868 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005869 case FCmpInst::FCMP_OGE:
5870 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5871 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005872 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005873 case FCmpInst::FCMP_OLT:
5874 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5875 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005876 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005877 case FCmpInst::FCMP_OLE:
5878 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5879 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005880 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005881 case FCmpInst::FCMP_ONE:
5882 Pred = ICmpInst::ICMP_NE;
5883 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005884 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005885 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005886 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005888 }
5889
5890 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5891
5892 // Now we know that the APFloat is a normal number, zero or inf.
5893
Chris Lattner85162782008-05-20 03:50:52 +00005894 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005895 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005896 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005897
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005898 if (!LHSUnsigned) {
5899 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5900 // and large values.
5901 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5902 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5903 APFloat::rmNearestTiesToEven);
5904 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5905 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5906 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005907 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5908 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005909 }
5910 } else {
5911 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5912 // +INF and large values.
5913 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5914 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5915 APFloat::rmNearestTiesToEven);
5916 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5917 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5918 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005919 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5920 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005921 }
Chris Lattnera5406232008-05-19 20:18:56 +00005922 }
5923
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005924 if (!LHSUnsigned) {
5925 // See if the RHS value is < SignedMin.
5926 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5927 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5928 APFloat::rmNearestTiesToEven);
5929 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5930 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5931 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005932 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5933 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005934 }
Chris Lattnera5406232008-05-19 20:18:56 +00005935 }
5936
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005937 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5938 // [0, UMAX], but it may still be fractional. See if it is fractional by
5939 // casting the FP value to the integer value and back, checking for equality.
5940 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005941 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005942 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5943 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005944 if (!RHS.isZero()) {
5945 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005946 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5947 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005948 if (!Equal) {
5949 // If we had a comparison against a fractional value, we have to adjust
5950 // the compare predicate and sometimes the value. RHSC is rounded towards
5951 // zero at this point.
5952 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005953 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005954 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005955 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005956 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005957 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005958 case ICmpInst::ICMP_ULE:
5959 // (float)int <= 4.4 --> int <= 4
5960 // (float)int <= -4.4 --> false
5961 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005962 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005963 break;
5964 case ICmpInst::ICMP_SLE:
5965 // (float)int <= 4.4 --> int <= 4
5966 // (float)int <= -4.4 --> int < -4
5967 if (RHS.isNegative())
5968 Pred = ICmpInst::ICMP_SLT;
5969 break;
5970 case ICmpInst::ICMP_ULT:
5971 // (float)int < -4.4 --> false
5972 // (float)int < 4.4 --> int <= 4
5973 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005974 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005975 Pred = ICmpInst::ICMP_ULE;
5976 break;
5977 case ICmpInst::ICMP_SLT:
5978 // (float)int < -4.4 --> int < -4
5979 // (float)int < 4.4 --> int <= 4
5980 if (!RHS.isNegative())
5981 Pred = ICmpInst::ICMP_SLE;
5982 break;
5983 case ICmpInst::ICMP_UGT:
5984 // (float)int > 4.4 --> int > 4
5985 // (float)int > -4.4 --> true
5986 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005987 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005988 break;
5989 case ICmpInst::ICMP_SGT:
5990 // (float)int > 4.4 --> int > 4
5991 // (float)int > -4.4 --> int >= -4
5992 if (RHS.isNegative())
5993 Pred = ICmpInst::ICMP_SGE;
5994 break;
5995 case ICmpInst::ICMP_UGE:
5996 // (float)int >= -4.4 --> true
5997 // (float)int >= 4.4 --> int > 4
5998 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005999 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00006000 Pred = ICmpInst::ICMP_UGT;
6001 break;
6002 case ICmpInst::ICMP_SGE:
6003 // (float)int >= -4.4 --> int >= -4
6004 // (float)int >= 4.4 --> int > 4
6005 if (!RHS.isNegative())
6006 Pred = ICmpInst::ICMP_SGT;
6007 break;
6008 }
Chris Lattnera5406232008-05-19 20:18:56 +00006009 }
6010 }
6011
6012 // Lower this FP comparison into an appropriate integer version of the
6013 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006014 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00006015}
6016
Reid Spencere4d87aa2006-12-23 06:05:41 +00006017Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006018 bool Changed = false;
6019
6020 /// Orders the operands of the compare so that they are listed from most
6021 /// complex to least complex. This puts constants before unary operators,
6022 /// before binary operators.
6023 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6024 I.swapOperands();
6025 Changed = true;
6026 }
6027
Chris Lattner8b170942002-08-09 23:47:40 +00006028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00006029
Chris Lattner210c5d42009-11-09 23:55:12 +00006030 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6031 return ReplaceInstUsesWith(I, V);
6032
Chris Lattner58e97462007-01-14 19:42:17 +00006033 // Simplify 'fcmp pred X, X'
6034 if (Op0 == Op1) {
6035 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006036 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00006037 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6038 case FCmpInst::FCMP_ULT: // True if unordered or less than
6039 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6040 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6041 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6042 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00006043 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006044 return &I;
6045
6046 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6047 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6048 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6049 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6050 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6051 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00006052 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006053 return &I;
6054 }
6055 }
6056
Reid Spencere4d87aa2006-12-23 06:05:41 +00006057 // Handle fcmp with constant RHS
6058 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6059 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6060 switch (LHSI->getOpcode()) {
6061 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006062 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6063 // block. If in the same block, we're encouraging jump threading. If
6064 // not, we are just pessimizing the code by making an i1 phi.
6065 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006066 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006067 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006068 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006069 case Instruction::SIToFP:
6070 case Instruction::UIToFP:
6071 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6072 return NV;
6073 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006074 case Instruction::Select:
6075 // If either operand of the select is a constant, we can fold the
6076 // comparison into the select arms, which will cause one to be
6077 // constant folded and the select turned into a bitwise or.
6078 Value *Op1 = 0, *Op2 = 0;
6079 if (LHSI->hasOneUse()) {
6080 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6081 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006082 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006083 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006084 Op2 = Builder->CreateFCmp(I.getPredicate(),
6085 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006086 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6087 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006088 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006089 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006090 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6091 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006092 }
6093 }
6094
6095 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006096 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006097 break;
6098 }
6099 }
6100
6101 return Changed ? &I : 0;
6102}
6103
6104Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006105 bool Changed = false;
6106
6107 /// Orders the operands of the compare so that they are listed from most
6108 /// complex to least complex. This puts constants before unary operators,
6109 /// before binary operators.
6110 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6111 I.swapOperands();
6112 Changed = true;
6113 }
6114
Reid Spencere4d87aa2006-12-23 06:05:41 +00006115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006116
Chris Lattner210c5d42009-11-09 23:55:12 +00006117 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6118 return ReplaceInstUsesWith(I, V);
6119
6120 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006121
Reid Spencere4d87aa2006-12-23 06:05:41 +00006122 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006123 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006124 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006125 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006126 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006127 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006128 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006129 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006130 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006131 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006132
Reid Spencere4d87aa2006-12-23 06:05:41 +00006133 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006134 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006135 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006136 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006137 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006138 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006139 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006140 case ICmpInst::ICMP_SGT:
6141 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006142 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006143 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006144 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006145 return BinaryOperator::CreateAnd(Not, Op0);
6146 }
6147 case ICmpInst::ICMP_UGE:
6148 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6149 // FALL THROUGH
6150 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006151 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006152 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006153 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006154 case ICmpInst::ICMP_SGE:
6155 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6156 // FALL THROUGH
6157 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006158 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006159 return BinaryOperator::CreateOr(Not, Op0);
6160 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006161 }
Chris Lattner8b170942002-08-09 23:47:40 +00006162 }
6163
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 unsigned BitWidth = 0;
6165 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006166 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6167 else if (Ty->isIntOrIntVector())
6168 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169
6170 bool isSignBit = false;
6171
Dan Gohman81b28ce2008-09-16 18:46:06 +00006172 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006174 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006175
Chris Lattnerb6566012008-01-05 01:18:20 +00006176 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6177 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006178 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006179 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006180 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006181 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006182
Dan Gohman81b28ce2008-09-16 18:46:06 +00006183 // If we have an icmp le or icmp ge instruction, turn it into the
6184 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006185 // them being folded in the code below. The SimplifyICmpInst code has
6186 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006187 switch (I.getPredicate()) {
6188 default: break;
6189 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006190 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006191 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006192 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006193 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006194 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006195 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006196 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006197 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006198 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006199 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006200 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006201 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006202 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006203 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006204 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006205 }
6206
Chris Lattner183661e2008-07-11 05:40:05 +00006207 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006208 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006209 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6211 }
6212
6213 // See if we can fold the comparison based on range information we can get
6214 // by checking whether bits are known to be zero or one in the input.
6215 if (BitWidth != 0) {
6216 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6217 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6218
6219 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006220 isSignBit ? APInt::getSignBit(BitWidth)
6221 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006223 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 if (SimplifyDemandedBits(I.getOperandUse(1),
6225 APInt::getAllOnesValue(BitWidth),
6226 Op1KnownZero, Op1KnownOne, 0))
6227 return &I;
6228
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006229 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006230 // in. Compute the Min, Max and RHS values based on the known bits. For the
6231 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006232 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6233 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006234 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6236 Op0Min, Op0Max);
6237 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6238 Op1Min, Op1Max);
6239 } else {
6240 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6241 Op0Min, Op0Max);
6242 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6243 Op1Min, Op1Max);
6244 }
6245
Chris Lattner183661e2008-07-11 05:40:05 +00006246 // If Min and Max are known to be the same, then SimplifyDemandedBits
6247 // figured out that the LHS is a constant. Just constant fold this now so
6248 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006249 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006250 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006251 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006252 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006253 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006254 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255
Chris Lattner183661e2008-07-11 05:40:05 +00006256 // Based on the range information we know about the LHS, see if we can
6257 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006258 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006259 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006260 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006261 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006262 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006263 break;
6264 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006265 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006266 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006267 break;
6268 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006269 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006270 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006271 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006272 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006273 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006274 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006275 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6276 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006277 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006278 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006279
6280 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6281 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006282 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006283 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006284 }
Chris Lattner84dff672008-07-11 05:08:55 +00006285 break;
6286 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006287 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006288 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006289 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006290 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006291
6292 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006293 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006294 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6295 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006296 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006297 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006298
6299 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6300 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006301 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006302 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006303 }
Chris Lattner84dff672008-07-11 05:08:55 +00006304 break;
6305 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006306 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006307 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006308 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006309 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006310 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006311 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006312 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6313 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006314 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006315 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006316 }
Chris Lattner84dff672008-07-11 05:08:55 +00006317 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006318 case ICmpInst::ICMP_SGT:
6319 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006320 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006321 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006322 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006323
6324 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006325 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006326 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6327 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006328 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006329 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006330 }
6331 break;
6332 case ICmpInst::ICMP_SGE:
6333 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6334 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006335 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006336 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006337 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006338 break;
6339 case ICmpInst::ICMP_SLE:
6340 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6341 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006342 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006343 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006344 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006345 break;
6346 case ICmpInst::ICMP_UGE:
6347 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6348 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006349 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006350 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006351 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006352 break;
6353 case ICmpInst::ICMP_ULE:
6354 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6355 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006356 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006357 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006358 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006359 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006360 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006361
6362 // Turn a signed comparison into an unsigned one if both operands
6363 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006364 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006365 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6366 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006367 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006368 }
6369
6370 // Test if the ICmpInst instruction is used exclusively by a select as
6371 // part of a minimum or maximum operation. If so, refrain from doing
6372 // any other folding. This helps out other analyses which understand
6373 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6374 // and CodeGen. And in this case, at least one of the comparison
6375 // operands has at least one user besides the compare (the select),
6376 // which would often largely negate the benefit of folding anyway.
6377 if (I.hasOneUse())
6378 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6379 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6380 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6381 return 0;
6382
6383 // See if we are doing a comparison between a constant and an instruction that
6384 // can be folded into the comparison.
6385 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006386 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006387 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006388 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006389 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006390 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6391 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006392 }
6393
Chris Lattner01deb9d2007-04-03 17:43:25 +00006394 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006395 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6396 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6397 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006398 case Instruction::GetElementPtr:
6399 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006400 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006401 bool isAllZeros = true;
6402 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6403 if (!isa<Constant>(LHSI->getOperand(i)) ||
6404 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6405 isAllZeros = false;
6406 break;
6407 }
6408 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006409 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006410 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006411 }
6412 break;
6413
Chris Lattner6970b662005-04-23 15:31:55 +00006414 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006415 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006416 // block. If in the same block, we're encouraging jump threading. If
6417 // not, we are just pessimizing the code by making an i1 phi.
6418 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006419 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006420 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006421 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006422 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006423 // If either operand of the select is a constant, we can fold the
6424 // comparison into the select arms, which will cause one to be
6425 // constant folded and the select turned into a bitwise or.
6426 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006427 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6428 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6429 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6430 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6431
6432 // We only want to perform this transformation if it will not lead to
6433 // additional code. This is true if either both sides of the select
6434 // fold to a constant (in which case the icmp is replaced with a select
6435 // which will usually simplify) or this is the only user of the
6436 // select (in which case we are trading a select+icmp for a simpler
6437 // select+icmp).
6438 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6439 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006440 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6441 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006442 if (!Op2)
6443 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6444 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006445 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006446 }
Chris Lattner6970b662005-04-23 15:31:55 +00006447 break;
6448 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006449 case Instruction::Call:
6450 // If we have (malloc != null), and if the malloc has a single use, we
6451 // can assume it is successful and remove the malloc.
6452 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6453 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006454 // Need to explicitly erase malloc call here, instead of adding it to
6455 // Worklist, because it won't get DCE'd from the Worklist since
6456 // isInstructionTriviallyDead() returns false for function calls.
6457 // It is OK to replace LHSI/MallocCall with Undef because the
6458 // instruction that uses it will be erased via Worklist.
6459 if (extractMallocCall(LHSI)) {
6460 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6461 EraseInstFromFunction(*LHSI);
6462 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006463 ConstantInt::get(Type::getInt1Ty(*Context),
6464 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006465 }
6466 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6467 if (MallocCall->hasOneUse()) {
6468 MallocCall->replaceAllUsesWith(
6469 UndefValue::get(MallocCall->getType()));
6470 EraseInstFromFunction(*MallocCall);
6471 Worklist.Add(LHSI); // The malloc's bitcast use.
6472 return ReplaceInstUsesWith(I,
6473 ConstantInt::get(Type::getInt1Ty(*Context),
6474 !I.isTrueWhenEqual()));
6475 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006476 }
6477 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006478 }
Chris Lattner6970b662005-04-23 15:31:55 +00006479 }
6480
Reid Spencere4d87aa2006-12-23 06:05:41 +00006481 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006482 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006483 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006484 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006485 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006486 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6487 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006488 return NI;
6489
Reid Spencere4d87aa2006-12-23 06:05:41 +00006490 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006491 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6492 // now.
6493 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6494 if (isa<PointerType>(Op0->getType()) &&
6495 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006496 // We keep moving the cast from the left operand over to the right
6497 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006498 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006499
Chris Lattner57d86372007-01-06 01:45:59 +00006500 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6501 // so eliminate it as well.
6502 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6503 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006504
Chris Lattnerde90b762003-11-03 04:25:02 +00006505 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006506 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006507 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006508 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006509 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006510 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006511 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006512 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006513 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006514 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006515 }
Chris Lattner57d86372007-01-06 01:45:59 +00006516 }
6517
6518 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006519 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006520 // This comes up when you have code like
6521 // int X = A < B;
6522 // if (X) ...
6523 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006524 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006525 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006526 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006527 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006528 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006529
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006530 // See if it's the same type of instruction on the left and right.
6531 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6532 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006533 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006534 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006535 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006536 default: break;
6537 case Instruction::Add:
6538 case Instruction::Sub:
6539 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006540 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006541 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006542 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006543 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6544 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6545 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006546 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006547 ? I.getUnsignedPredicate()
6548 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006549 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006550 Op1I->getOperand(0));
6551 }
6552
6553 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006554 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006555 ? I.getUnsignedPredicate()
6556 : I.getSignedPredicate();
6557 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006558 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006559 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006560 }
6561 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006562 break;
6563 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006564 if (!I.isEquality())
6565 break;
6566
Nick Lewycky5d52c452008-08-21 05:56:10 +00006567 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6568 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6569 // Mask = -1 >> count-trailing-zeros(Cst).
6570 if (!CI->isZero() && !CI->isOne()) {
6571 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006572 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006573 APInt::getLowBitsSet(AP.getBitWidth(),
6574 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006575 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006576 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6577 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006578 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006579 }
6580 }
6581 break;
6582 }
6583 }
6584 }
6585 }
6586
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006587 // ~x < ~y --> y < x
6588 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006589 if (match(Op0, m_Not(m_Value(A))) &&
6590 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006591 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006592 }
6593
Chris Lattner65b72ba2006-09-18 04:22:48 +00006594 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006595 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006596
6597 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006598 if (match(Op0, m_Neg(m_Value(A))) &&
6599 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006600 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006601
Dan Gohman4ae51262009-08-12 16:23:25 +00006602 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006603 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6604 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006605 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006606 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006607 }
6608
Dan Gohman4ae51262009-08-12 16:23:25 +00006609 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006610 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006611 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006612 if (match(B, m_ConstantInt(C1)) &&
6613 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006614 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006615 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006616 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6617 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006618 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006619
6620 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006621 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6622 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6623 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6624 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006625 }
6626 }
6627
Dan Gohman4ae51262009-08-12 16:23:25 +00006628 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006629 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006630 // A == (A^B) -> B == 0
6631 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006632 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006633 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006634 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006635
6636 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006637 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006638 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006639 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006640
6641 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006642 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006643 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006644 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006645
Chris Lattner9c2328e2006-11-14 06:06:06 +00006646 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6647 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006648 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6649 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006650 Value *X = 0, *Y = 0, *Z = 0;
6651
6652 if (A == C) {
6653 X = B; Y = D; Z = A;
6654 } else if (A == D) {
6655 X = B; Y = C; Z = A;
6656 } else if (B == C) {
6657 X = A; Y = D; Z = B;
6658 } else if (B == D) {
6659 X = A; Y = C; Z = B;
6660 }
6661
6662 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006663 Op1 = Builder->CreateXor(X, Y, "tmp");
6664 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006665 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006666 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006667 return &I;
6668 }
6669 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006670 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006671
6672 {
6673 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006674 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006675 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006676 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6677
Chris Lattner2799baf2009-12-21 03:19:28 +00006678 // icmp X, X+Cst
6679 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006680 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006681 }
Chris Lattner7e708292002-06-25 16:13:24 +00006682 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006683}
6684
Chris Lattner2799baf2009-12-21 03:19:28 +00006685/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6686Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6687 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006688 ICmpInst::Predicate Pred,
6689 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006690 // If we have X+0, exit early (simplifying logic below) and let it get folded
6691 // elsewhere. icmp X+0, X -> icmp X, X
6692 if (CI->isZero()) {
6693 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6694 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6695 }
6696
6697 // (X+4) == X -> false.
6698 if (Pred == ICmpInst::ICMP_EQ)
6699 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6700
6701 // (X+4) != X -> true.
6702 if (Pred == ICmpInst::ICMP_NE)
6703 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006704
6705 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6706 bool isNUW = false, isNSW = false;
6707 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6708 isNUW = Add->hasNoUnsignedWrap();
6709 isNSW = Add->hasNoSignedWrap();
6710 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006711
6712 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6713 // so the values can never be equal. Similiarly for all other "or equals"
6714 // operators.
6715
6716 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6717 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6718 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6719 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006720 // If this is an NUW add, then this is always false.
6721 if (isNUW)
6722 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6723
Chris Lattner2799baf2009-12-21 03:19:28 +00006724 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6725 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6726 }
6727
6728 // (X+1) >u X --> X <u (0-1) --> X != 255
6729 // (X+2) >u X --> X <u (0-2) --> X <u 254
6730 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006731 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6732 // If this is an NUW add, then this is always true.
6733 if (isNUW)
6734 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006735 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006736 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006737
6738 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6739 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6740 APInt::getSignedMaxValue(BitWidth));
6741
6742 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6743 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6744 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6745 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6746 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6747 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00006748 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6749 // If this is an NSW add, then we have two cases: if the constant is
6750 // positive, then this is always false, if negative, this is always true.
6751 if (isNSW) {
6752 bool isTrue = CI->getValue().isNegative();
6753 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6754 }
6755
Chris Lattner2799baf2009-12-21 03:19:28 +00006756 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006757 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006758
6759 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6760 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6761 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6762 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6763 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6764 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00006765
6766 // If this is an NSW add, then we have two cases: if the constant is
6767 // positive, then this is always true, if negative, this is always false.
6768 if (isNSW) {
6769 bool isTrue = !CI->getValue().isNegative();
6770 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6771 }
6772
Chris Lattner2799baf2009-12-21 03:19:28 +00006773 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6774 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6775 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6776}
Chris Lattner562ef782007-06-20 23:46:26 +00006777
6778/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6779/// and CmpRHS are both known to be integer constants.
6780Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6781 ConstantInt *DivRHS) {
6782 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6783 const APInt &CmpRHSV = CmpRHS->getValue();
6784
6785 // FIXME: If the operand types don't match the type of the divide
6786 // then don't attempt this transform. The code below doesn't have the
6787 // logic to deal with a signed divide and an unsigned compare (and
6788 // vice versa). This is because (x /s C1) <s C2 produces different
6789 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6790 // (x /u C1) <u C2. Simply casting the operands and result won't
6791 // work. :( The if statement below tests that condition and bails
6792 // if it finds it.
6793 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006794 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006795 return 0;
6796 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006797 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006798 if (DivIsSigned && DivRHS->isAllOnesValue())
6799 return 0; // The overflow computation also screws up here
6800 if (DivRHS->isOne())
6801 return 0; // Not worth bothering, and eliminates some funny cases
6802 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006803
6804 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6805 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6806 // C2 (CI). By solving for X we can turn this into a range check
6807 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006808 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006809
6810 // Determine if the product overflows by seeing if the product is
6811 // not equal to the divide. Make sure we do the same kind of divide
6812 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006813 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6814 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006815
6816 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006817 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006818
Chris Lattner1dbfd482007-06-21 18:11:19 +00006819 // Figure out the interval that is being checked. For example, a comparison
6820 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6821 // Compute this interval based on the constants involved and the signedness of
6822 // the compare/divide. This computes a half-open interval, keeping track of
6823 // whether either value in the interval overflows. After analysis each
6824 // overflow variable is set to 0 if it's corresponding bound variable is valid
6825 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6826 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006827 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006828
Chris Lattner562ef782007-06-20 23:46:26 +00006829 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006830 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006831 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006832 HiOverflow = LoOverflow = ProdOV;
6833 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006834 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006835 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006836 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006837 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006838 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006839 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006840 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006841 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6842 HiOverflow = LoOverflow = ProdOV;
6843 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006844 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006845 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006846 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006847 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006848 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6849 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006850 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006851 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006852 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006853 true) ? -1 : 0;
6854 }
Chris Lattner562ef782007-06-20 23:46:26 +00006855 }
Dan Gohman76491272008-02-13 22:09:18 +00006856 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006857 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006858 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006859 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006860 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006861 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6862 HiOverflow = 1; // [INTMIN+1, overflow)
6863 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6864 }
Dan Gohman76491272008-02-13 22:09:18 +00006865 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006866 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006867 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006868 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006869 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006870 LoOverflow = AddWithOverflow(LoBound, HiBound,
6871 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006872 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006873 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6874 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006875 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006876 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006877 }
6878
Chris Lattner1dbfd482007-06-21 18:11:19 +00006879 // Dividing by a negative swaps the condition. LT <-> GT
6880 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006881 }
6882
6883 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006884 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006885 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006886 case ICmpInst::ICMP_EQ:
6887 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006888 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006889 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006890 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006891 ICmpInst::ICMP_UGE, X, LoBound);
6892 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006893 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006894 ICmpInst::ICMP_ULT, X, HiBound);
6895 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006896 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006897 case ICmpInst::ICMP_NE:
6898 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006899 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006900 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006901 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006902 ICmpInst::ICMP_ULT, X, LoBound);
6903 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006904 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006905 ICmpInst::ICMP_UGE, X, HiBound);
6906 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006907 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006908 case ICmpInst::ICMP_ULT:
6909 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006910 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006911 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006912 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006913 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006914 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006915 case ICmpInst::ICMP_UGT:
6916 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006917 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006918 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006919 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006920 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006921 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006922 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006923 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006924 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006925 }
6926}
6927
6928
Chris Lattner01deb9d2007-04-03 17:43:25 +00006929/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6930///
6931Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6932 Instruction *LHSI,
6933 ConstantInt *RHS) {
6934 const APInt &RHSV = RHS->getValue();
6935
6936 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006937 case Instruction::Trunc:
6938 if (ICI.isEquality() && LHSI->hasOneUse()) {
6939 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6940 // of the high bits truncated out of x are known.
6941 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6942 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6943 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6944 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6945 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6946
6947 // If all the high bits are known, we can do this xform.
6948 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6949 // Pull in the high bits from known-ones set.
6950 APInt NewRHS(RHS->getValue());
6951 NewRHS.zext(SrcBits);
6952 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006953 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006954 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006955 }
6956 }
6957 break;
6958
Duncan Sands0091bf22007-04-04 06:42:45 +00006959 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006960 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6961 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6962 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006963 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6964 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006965 Value *CompareVal = LHSI->getOperand(0);
6966
6967 // If the sign bit of the XorCST is not set, there is no change to
6968 // the operation, just stop using the Xor.
6969 if (!XorCST->getValue().isNegative()) {
6970 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006971 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006972 return &ICI;
6973 }
6974
6975 // Was the old condition true if the operand is positive?
6976 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6977
6978 // If so, the new one isn't.
6979 isTrueIfPositive ^= true;
6980
6981 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006982 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006983 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006984 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006985 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006986 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006987 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006988
6989 if (LHSI->hasOneUse()) {
6990 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6991 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6992 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006993 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006994 ? ICI.getUnsignedPredicate()
6995 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006996 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006997 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006998 }
6999
7000 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00007001 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00007002 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007003 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007004 ? ICI.getUnsignedPredicate()
7005 : ICI.getSignedPredicate();
7006 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007007 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007008 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007009 }
7010 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007011 }
7012 break;
7013 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7014 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7015 LHSI->getOperand(0)->hasOneUse()) {
7016 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7017
7018 // If the LHS is an AND of a truncating cast, we can widen the
7019 // and/compare to be the input width without changing the value
7020 // produced, eliminating a cast.
7021 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7022 // We can do this transformation if either the AND constant does not
7023 // have its sign bit set or if it is an equality comparison.
7024 // Extending a relational comparison when we're checking the sign
7025 // bit would not work.
7026 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00007027 (ICI.isEquality() ||
7028 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007029 uint32_t BitWidth =
7030 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7031 APInt NewCST = AndCST->getValue();
7032 NewCST.zext(BitWidth);
7033 APInt NewCI = RHSV;
7034 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00007035 Value *NewAnd =
7036 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007037 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007038 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00007039 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007040 }
7041 }
7042
7043 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7044 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7045 // happens a LOT in code produced by the C front-end, for bitfield
7046 // access.
7047 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7048 if (Shift && !Shift->isShift())
7049 Shift = 0;
7050
7051 ConstantInt *ShAmt;
7052 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7053 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7054 const Type *AndTy = AndCST->getType(); // Type of the and.
7055
7056 // We can fold this as long as we can't shift unknown bits
7057 // into the mask. This can only happen with signed shift
7058 // rights, as they sign-extend.
7059 if (ShAmt) {
7060 bool CanFold = Shift->isLogicalShift();
7061 if (!CanFold) {
7062 // To test for the bad case of the signed shr, see if any
7063 // of the bits shifted in could be tested after the mask.
7064 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7065 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7066
7067 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7068 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7069 AndCST->getValue()) == 0)
7070 CanFold = true;
7071 }
7072
7073 if (CanFold) {
7074 Constant *NewCst;
7075 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007076 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007078 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007079
7080 // Check to see if we are shifting out any of the bits being
7081 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007082 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007083 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007084 // If we shifted bits out, the fold is not going to work out.
7085 // As a special case, check to see if this means that the
7086 // result is always true or false now.
7087 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007088 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007089 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007090 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007091 } else {
7092 ICI.setOperand(1, NewCst);
7093 Constant *NewAndCST;
7094 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007095 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007096 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007097 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007098 LHSI->setOperand(1, NewAndCST);
7099 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007100 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007101 return &ICI;
7102 }
7103 }
7104 }
7105
7106 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7107 // preferable because it allows the C<<Y expression to be hoisted out
7108 // of a loop if Y is invariant and X is not.
7109 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007110 ICI.isEquality() && !Shift->isArithmeticShift() &&
7111 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007112 // Compute C << Y.
7113 Value *NS;
7114 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007115 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007116 } else {
7117 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007118 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120
7121 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007122 Value *NewAnd =
7123 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124
7125 ICI.setOperand(0, NewAnd);
7126 return &ICI;
7127 }
7128 }
7129 break;
7130
Chris Lattnera0141b92007-07-15 20:42:37 +00007131 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7132 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7133 if (!ShAmt) break;
7134
7135 uint32_t TypeBits = RHSV.getBitWidth();
7136
7137 // Check that the shift amount is in range. If not, don't perform
7138 // undefined shifts. When the shift is visited it will be
7139 // simplified.
7140 if (ShAmt->uge(TypeBits))
7141 break;
7142
7143 if (ICI.isEquality()) {
7144 // If we are comparing against bits always shifted out, the
7145 // comparison cannot succeed.
7146 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007147 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007148 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007149 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7150 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007151 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007152 return ReplaceInstUsesWith(ICI, Cst);
7153 }
7154
7155 if (LHSI->hasOneUse()) {
7156 // Otherwise strength reduce the shift into an and.
7157 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7158 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007159 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007160 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007161
Chris Lattner74381062009-08-30 07:44:24 +00007162 Value *And =
7163 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007164 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007165 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007166 }
7167 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007168
7169 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7170 bool TrueIfSigned = false;
7171 if (LHSI->hasOneUse() &&
7172 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7173 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007174 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007175 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007176 Value *And =
7177 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007178 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007179 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007180 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007181 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007182 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007183
7184 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007185 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007186 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007187 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007188 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007189
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007190 // Check that the shift amount is in range. If not, don't perform
7191 // undefined shifts. When the shift is visited it will be
7192 // simplified.
7193 uint32_t TypeBits = RHSV.getBitWidth();
7194 if (ShAmt->uge(TypeBits))
7195 break;
7196
7197 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007198
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007199 // If we are comparing against bits always shifted out, the
7200 // comparison cannot succeed.
7201 APInt Comp = RHSV << ShAmtVal;
7202 if (LHSI->getOpcode() == Instruction::LShr)
7203 Comp = Comp.lshr(ShAmtVal);
7204 else
7205 Comp = Comp.ashr(ShAmtVal);
7206
7207 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7208 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007209 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007210 return ReplaceInstUsesWith(ICI, Cst);
7211 }
7212
7213 // Otherwise, check to see if the bits shifted out are known to be zero.
7214 // If so, we can compare against the unshifted value:
7215 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007216 if (LHSI->hasOneUse() &&
7217 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007218 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007219 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007220 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007221 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007222
Evan Chengf30752c2008-04-23 00:38:06 +00007223 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007224 // Otherwise strength reduce the shift into an and.
7225 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007226 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007227
Chris Lattner74381062009-08-30 07:44:24 +00007228 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7229 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007230 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007231 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007232 }
7233 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007234 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007235
7236 case Instruction::SDiv:
7237 case Instruction::UDiv:
7238 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7239 // Fold this div into the comparison, producing a range check.
7240 // Determine, based on the divide type, what the range is being
7241 // checked. If there is an overflow on the low or high side, remember
7242 // it, otherwise compute the range [low, hi) bounding the new value.
7243 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007244 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7245 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7246 DivRHS))
7247 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007248 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007249
7250 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007251 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007252 if (!ICI.isEquality()) {
7253 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7254 if (!LHSC) break;
7255 const APInt &LHSV = LHSC->getValue();
7256
7257 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7258 .subtract(LHSV);
7259
Nick Lewycky4a134af2009-10-25 05:20:17 +00007260 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007261 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007262 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007263 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007264 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007265 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007266 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007267 }
7268 } else {
7269 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007270 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007271 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007272 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007273 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007274 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007275 }
7276 }
7277 }
7278 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007279 }
7280
7281 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7282 if (ICI.isEquality()) {
7283 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7284
7285 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7286 // the second operand is a constant, simplify a bit.
7287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7288 switch (BO->getOpcode()) {
7289 case Instruction::SRem:
7290 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7291 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7292 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7293 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007294 Value *NewRem =
7295 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7296 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007297 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007298 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007299 }
7300 }
7301 break;
7302 case Instruction::Add:
7303 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7304 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7305 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007306 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007307 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007308 } else if (RHSV == 0) {
7309 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7310 // efficiently invertible, or if the add has just this one use.
7311 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7312
Dan Gohman186a6362009-08-12 16:04:34 +00007313 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007314 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007315 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007316 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007317 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007318 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007319 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007320 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007321 }
7322 }
7323 break;
7324 case Instruction::Xor:
7325 // For the xor case, we can xor two constants together, eliminating
7326 // the explicit xor.
7327 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007328 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007329 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007330
7331 // FALLTHROUGH
7332 case Instruction::Sub:
7333 // Replace (([sub|xor] A, B) != 0) with (A != B)
7334 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007335 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007336 BO->getOperand(1));
7337 break;
7338
7339 case Instruction::Or:
7340 // If bits are being or'd in that are not present in the constant we
7341 // are comparing against, then the comparison could never succeed!
7342 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007343 Constant *NotCI = ConstantExpr::getNot(RHS);
7344 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007345 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007346 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007347 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007348 }
7349 break;
7350
7351 case Instruction::And:
7352 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7353 // If bits are being compared against that are and'd out, then the
7354 // comparison can never succeed!
7355 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007356 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007357 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007358 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007359
7360 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7361 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007362 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007363 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007364 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007365
7366 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007367 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007368 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007369 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007370 ICmpInst::Predicate pred = isICMP_NE ?
7371 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007372 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007373 }
7374
7375 // ((X & ~7) == 0) --> X < 8
7376 if (RHSV == 0 && isHighOnes(BOC)) {
7377 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007378 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007379 ICmpInst::Predicate pred = isICMP_NE ?
7380 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007381 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007382 }
7383 }
7384 default: break;
7385 }
7386 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7387 // Handle icmp {eq|ne} <intrinsic>, intcst.
7388 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007389 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007390 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007391 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007392 return &ICI;
7393 }
7394 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007395 }
7396 return 0;
7397}
7398
7399/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7400/// We only handle extending casts so far.
7401///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007402Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7403 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007404 Value *LHSCIOp = LHSCI->getOperand(0);
7405 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007406 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007407 Value *RHSCIOp;
7408
Chris Lattner8c756c12007-05-05 22:41:33 +00007409 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7410 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007411 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7412 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007413 cast<IntegerType>(DestTy)->getBitWidth()) {
7414 Value *RHSOp = 0;
7415 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007416 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007417 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7418 RHSOp = RHSC->getOperand(0);
7419 // If the pointer types don't match, insert a bitcast.
7420 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007421 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007422 }
7423
7424 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007425 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007426 }
7427
7428 // The code below only handles extension cast instructions, so far.
7429 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007430 if (LHSCI->getOpcode() != Instruction::ZExt &&
7431 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007432 return 0;
7433
Reid Spencere4d87aa2006-12-23 06:05:41 +00007434 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007435 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007436
Reid Spencere4d87aa2006-12-23 06:05:41 +00007437 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007438 // Not an extension from the same type?
7439 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007440 if (RHSCIOp->getType() != LHSCIOp->getType())
7441 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007442
Nick Lewycky4189a532008-01-28 03:48:02 +00007443 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007444 // and the other is a zext), then we can't handle this.
7445 if (CI->getOpcode() != LHSCI->getOpcode())
7446 return 0;
7447
Nick Lewycky4189a532008-01-28 03:48:02 +00007448 // Deal with equality cases early.
7449 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007450 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007451
7452 // A signed comparison of sign extended values simplifies into a
7453 // signed comparison.
7454 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007455 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007456
7457 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007458 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007459 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007460
Reid Spencere4d87aa2006-12-23 06:05:41 +00007461 // If we aren't dealing with a constant on the RHS, exit early
7462 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7463 if (!CI)
7464 return 0;
7465
7466 // Compute the constant that would happen if we truncated to SrcTy then
7467 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007468 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7469 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007470 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007471
7472 // If the re-extended constant didn't change...
7473 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007474 // Deal with equality cases early.
7475 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007476 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007477
7478 // A signed comparison of sign extended values simplifies into a
7479 // signed comparison.
7480 if (isSignedExt && isSignedCmp)
7481 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7482
7483 // The other three cases all fold into an unsigned comparison.
7484 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007485 }
7486
7487 // The re-extended constant changed so the constant cannot be represented
7488 // in the shorter type. Consequently, we cannot emit a simple comparison.
7489
7490 // First, handle some easy cases. We know the result cannot be equal at this
7491 // point so handle the ICI.isEquality() cases
7492 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007493 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007494 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007495 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007496
7497 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7498 // should have been folded away previously and not enter in here.
7499 Value *Result;
7500 if (isSignedCmp) {
7501 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007502 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007503 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007504 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007505 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007506 } else {
7507 // We're performing an unsigned comparison.
7508 if (isSignedExt) {
7509 // We're performing an unsigned comp with a sign extended value.
7510 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007511 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007512 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007513 } else {
7514 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007515 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007516 }
7517 }
7518
7519 // Finally, return the value computed.
7520 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007521 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007522 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007523
7524 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7525 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7526 "ICmp should be folded!");
7527 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007528 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007529 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007530}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007531
Reid Spencer832254e2007-02-02 02:16:23 +00007532Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7533 return commonShiftTransforms(I);
7534}
7535
7536Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7537 return commonShiftTransforms(I);
7538}
7539
7540Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007541 if (Instruction *R = commonShiftTransforms(I))
7542 return R;
7543
7544 Value *Op0 = I.getOperand(0);
7545
7546 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7547 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7548 if (CSI->isAllOnesValue())
7549 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007550
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007551 // See if we can turn a signed shr into an unsigned shr.
7552 if (MaskedValueIsZero(Op0,
7553 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7554 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7555
7556 // Arithmetic shifting an all-sign-bit value is a no-op.
7557 unsigned NumSignBits = ComputeNumSignBits(Op0);
7558 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7559 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007560
Chris Lattner348f6652007-12-06 01:59:46 +00007561 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007562}
7563
7564Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7565 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007566 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007567
7568 // shl X, 0 == X and shr X, 0 == X
7569 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007570 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7571 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007572 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007573
Reid Spencere4d87aa2006-12-23 06:05:41 +00007574 if (isa<UndefValue>(Op0)) {
7575 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007576 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007577 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007578 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007579 }
7580 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007581 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7582 return ReplaceInstUsesWith(I, Op0);
7583 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007584 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007585 }
7586
Dan Gohman9004c8a2009-05-21 02:28:33 +00007587 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007588 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007589 return &I;
7590
Chris Lattner2eefe512004-04-09 19:05:30 +00007591 // Try to fold constant and into select arguments.
7592 if (isa<Constant>(Op0))
7593 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007594 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007595 return R;
7596
Reid Spencerb83eb642006-10-20 07:07:24 +00007597 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007598 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7599 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007600 return 0;
7601}
7602
Reid Spencerb83eb642006-10-20 07:07:24 +00007603Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007604 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007605 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007606
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007607 // See if we can simplify any instructions used by the instruction whose sole
7608 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007609 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007610
Dan Gohmana119de82009-06-14 23:30:43 +00007611 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7612 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007613 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007614 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007615 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007616 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007617 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007618 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007619 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007620 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007621 }
7622
7623 // ((X*C1) << C2) == (X * (C1 << C2))
7624 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7625 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7626 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007627 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007628 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007629
7630 // Try to fold constant and into select arguments.
7631 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7632 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7633 return R;
7634 if (isa<PHINode>(Op0))
7635 if (Instruction *NV = FoldOpIntoPhi(I))
7636 return NV;
7637
Chris Lattner8999dd32007-12-22 09:07:47 +00007638 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7639 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7640 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7641 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7642 // place. Don't try to do this transformation in this case. Also, we
7643 // require that the input operand is a shift-by-constant so that we have
7644 // confidence that the shifts will get folded together. We could do this
7645 // xform in more cases, but it is unlikely to be profitable.
7646 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7647 isa<ConstantInt>(TrOp->getOperand(1))) {
7648 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007649 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007650 // (shift2 (shift1 & 0x00FF), c2)
7651 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007652
7653 // For logical shifts, the truncation has the effect of making the high
7654 // part of the register be zeros. Emulate this by inserting an AND to
7655 // clear the top bits as needed. This 'and' will usually be zapped by
7656 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007657 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7658 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007659 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7660
7661 // The mask we constructed says what the trunc would do if occurring
7662 // between the shifts. We want to know the effect *after* the second
7663 // shift. We know that it is a logical shift by a constant, so adjust the
7664 // mask as appropriate.
7665 if (I.getOpcode() == Instruction::Shl)
7666 MaskV <<= Op1->getZExtValue();
7667 else {
7668 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7669 MaskV = MaskV.lshr(Op1->getZExtValue());
7670 }
7671
Chris Lattner74381062009-08-30 07:44:24 +00007672 // shift1 & 0x00FF
7673 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7674 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007675
7676 // Return the value truncated to the interesting size.
7677 return new TruncInst(And, I.getType());
7678 }
7679 }
7680
Chris Lattner4d5542c2006-01-06 07:12:35 +00007681 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007682 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7683 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7684 Value *V1, *V2;
7685 ConstantInt *CC;
7686 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007687 default: break;
7688 case Instruction::Add:
7689 case Instruction::And:
7690 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007691 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007692 // These operators commute.
7693 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007694 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007695 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007696 m_Specific(Op1)))) {
7697 Value *YS = // (Y << C)
7698 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7699 // (X + (Y << C))
7700 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7701 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007702 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007703 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007704 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007705 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007706
Chris Lattner150f12a2005-09-18 06:30:59 +00007707 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007708 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007709 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007710 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007711 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007712 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007713 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007714 Value *YS = // (Y << C)
7715 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7716 Op0BO->getName());
7717 // X & (CC << C)
7718 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7719 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007720 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007721 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007722 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007723
Reid Spencera07cb7d2007-02-02 14:41:37 +00007724 // FALL THROUGH.
7725 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007726 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007727 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007728 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007729 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007730 Value *YS = // (Y << C)
7731 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7732 // (X + (Y << C))
7733 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7734 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007735 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007736 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007737 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007738 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007739
Chris Lattner13d4ab42006-05-31 21:14:00 +00007740 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007741 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7742 match(Op0BO->getOperand(0),
7743 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007744 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007745 cast<BinaryOperator>(Op0BO->getOperand(0))
7746 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007747 Value *YS = // (Y << C)
7748 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7749 // X & (CC << C)
7750 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7751 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007752
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007753 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007754 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007755
Chris Lattner11021cb2005-09-18 05:12:10 +00007756 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007757 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007758 }
7759
7760
7761 // If the operand is an bitwise operator with a constant RHS, and the
7762 // shift is the only use, we can pull it out of the shift.
7763 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7764 bool isValid = true; // Valid only for And, Or, Xor
7765 bool highBitSet = false; // Transform if high bit of constant set?
7766
7767 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007768 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007769 case Instruction::Add:
7770 isValid = isLeftShift;
7771 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007772 case Instruction::Or:
7773 case Instruction::Xor:
7774 highBitSet = false;
7775 break;
7776 case Instruction::And:
7777 highBitSet = true;
7778 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007779 }
7780
7781 // If this is a signed shift right, and the high bit is modified
7782 // by the logical operation, do not perform the transformation.
7783 // The highBitSet boolean indicates the value of the high bit of
7784 // the constant which would cause it to be modified for this
7785 // operation.
7786 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007787 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007788 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007789
7790 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007791 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007792
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007793 Value *NewShift =
7794 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007795 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007796
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007797 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007798 NewRHS);
7799 }
7800 }
7801 }
7802 }
7803
Chris Lattnerad0124c2006-01-06 07:52:12 +00007804 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007805 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7806 if (ShiftOp && !ShiftOp->isShift())
7807 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007808
Reid Spencerb83eb642006-10-20 07:07:24 +00007809 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007810 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007811 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7812 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007813 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7814 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7815 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007816
Zhou Sheng4351c642007-04-02 08:20:41 +00007817 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007818
7819 const IntegerType *Ty = cast<IntegerType>(I.getType());
7820
7821 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007822 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007823 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7824 // saturates.
7825 if (AmtSum >= TypeBits) {
7826 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007827 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007828 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7829 }
7830
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007831 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007832 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007833 }
7834
7835 if (ShiftOp->getOpcode() == Instruction::LShr &&
7836 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007837 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007838 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007839
Chris Lattnerb87056f2007-02-05 00:57:54 +00007840 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007841 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007842 }
7843
7844 if (ShiftOp->getOpcode() == Instruction::AShr &&
7845 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007846 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007847 if (AmtSum >= TypeBits)
7848 AmtSum = TypeBits-1;
7849
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007850 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007851
Zhou Shenge9e03f62007-03-28 15:02:20 +00007852 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007853 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007854 }
7855
Chris Lattnerb87056f2007-02-05 00:57:54 +00007856 // Okay, if we get here, one shift must be left, and the other shift must be
7857 // right. See if the amounts are equal.
7858 if (ShiftAmt1 == ShiftAmt2) {
7859 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7860 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007861 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007862 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007863 }
7864 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7865 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007866 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007867 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007868 }
7869 // We can simplify ((X << C) >>s C) into a trunc + sext.
7870 // NOTE: we could do this for any C, but that would make 'unusual' integer
7871 // types. For now, just stick to ones well-supported by the code
7872 // generators.
7873 const Type *SExtType = 0;
7874 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007875 case 1 :
7876 case 8 :
7877 case 16 :
7878 case 32 :
7879 case 64 :
7880 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007881 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007882 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007883 default: break;
7884 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007885 if (SExtType)
7886 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007887 // Otherwise, we can't handle it yet.
7888 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007889 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007890
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007891 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007892 if (I.getOpcode() == Instruction::Shl) {
7893 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7894 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007895 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007896
Reid Spencer55702aa2007-03-25 21:11:44 +00007897 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007898 return BinaryOperator::CreateAnd(Shift,
7899 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007900 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007901
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007902 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007903 if (I.getOpcode() == Instruction::LShr) {
7904 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007905 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007906
Reid Spencerd5e30f02007-03-26 17:18:58 +00007907 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007908 return BinaryOperator::CreateAnd(Shift,
7909 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007910 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007911
7912 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7913 } else {
7914 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007915 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007916
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007917 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007918 if (I.getOpcode() == Instruction::Shl) {
7919 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7920 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007921 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7922 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007923
Reid Spencer55702aa2007-03-25 21:11:44 +00007924 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007925 return BinaryOperator::CreateAnd(Shift,
7926 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007927 }
7928
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007929 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007930 if (I.getOpcode() == Instruction::LShr) {
7931 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007932 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007933
Reid Spencer68d27cf2007-03-26 23:45:51 +00007934 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007935 return BinaryOperator::CreateAnd(Shift,
7936 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007937 }
7938
7939 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007940 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007941 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007942 return 0;
7943}
7944
Chris Lattnera1be5662002-05-02 17:06:02 +00007945
Chris Lattnercfd65102005-10-29 04:36:15 +00007946/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7947/// expression. If so, decompose it, returning some value X, such that Val is
7948/// X*Scale+Offset.
7949///
7950static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007951 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007952 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7953 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007954 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007955 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007956 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007957 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007958 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7959 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7960 if (I->getOpcode() == Instruction::Shl) {
7961 // This is a value scaled by '1 << the shift amt'.
7962 Scale = 1U << RHS->getZExtValue();
7963 Offset = 0;
7964 return I->getOperand(0);
7965 } else if (I->getOpcode() == Instruction::Mul) {
7966 // This value is scaled by 'RHS'.
7967 Scale = RHS->getZExtValue();
7968 Offset = 0;
7969 return I->getOperand(0);
7970 } else if (I->getOpcode() == Instruction::Add) {
7971 // We have X+C. Check to see if we really have (X*C2)+C1,
7972 // where C1 is divisible by C2.
7973 unsigned SubScale;
7974 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007975 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7976 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007977 Offset += RHS->getZExtValue();
7978 Scale = SubScale;
7979 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007980 }
7981 }
7982 }
7983
7984 // Otherwise, we can't look past this.
7985 Scale = 1;
7986 Offset = 0;
7987 return Val;
7988}
7989
7990
Chris Lattnerb3f83972005-10-24 06:03:58 +00007991/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7992/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007993Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007994 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007995 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007996
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007997 BuilderTy AllocaBuilder(*Builder);
7998 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7999
Chris Lattnerb53c2382005-10-24 06:22:12 +00008000 // Remove any uses of AI that are dead.
8001 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00008002
Chris Lattnerb53c2382005-10-24 06:22:12 +00008003 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8004 Instruction *User = cast<Instruction>(*UI++);
8005 if (isInstructionTriviallyDead(User)) {
8006 while (UI != E && *UI == User)
8007 ++UI; // If this instruction uses AI more than once, don't break UI.
8008
Chris Lattnerb53c2382005-10-24 06:22:12 +00008009 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008010 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008011 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00008012 }
8013 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008014
8015 // This requires TargetData to get the alloca alignment and size information.
8016 if (!TD) return 0;
8017
Chris Lattnerb3f83972005-10-24 06:03:58 +00008018 // Get the type really allocated and the type casted to.
8019 const Type *AllocElTy = AI.getAllocatedType();
8020 const Type *CastElTy = PTy->getElementType();
8021 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008022
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008023 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8024 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00008025 if (CastElTyAlign < AllocElTyAlign) return 0;
8026
Chris Lattner39387a52005-10-24 06:35:18 +00008027 // If the allocation has multiple uses, only promote it if we are strictly
8028 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00008029 // same, we open the door to infinite loops of various kinds. (A reference
8030 // from a dbg.declare doesn't count as a use for this purpose.)
8031 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8032 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00008033
Duncan Sands777d2302009-05-09 07:06:46 +00008034 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8035 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008036 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008037
Chris Lattner455fcc82005-10-29 03:19:53 +00008038 // See if we can satisfy the modulus by pulling a scale out of the array
8039 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008040 unsigned ArraySizeScale;
8041 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008042 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00008043 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8044 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00008045
Chris Lattner455fcc82005-10-29 03:19:53 +00008046 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8047 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008048 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8049 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008050
Chris Lattner455fcc82005-10-29 03:19:53 +00008051 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8052 Value *Amt = 0;
8053 if (Scale == 1) {
8054 Amt = NumElements;
8055 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00008056 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008057 // Insert before the alloca, not before the cast.
8058 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008059 }
8060
Jeff Cohen86796be2007-04-04 16:58:57 +00008061 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008062 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008063 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008064 }
8065
Victor Hernandez7b929da2009-10-23 21:09:37 +00008066 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008067 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008068 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008069
Dale Johannesena0a66372009-03-05 00:39:02 +00008070 // If the allocation has one real use plus a dbg.declare, just remove the
8071 // declare.
8072 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8073 EraseInstFromFunction(*DI);
8074 }
8075 // If the allocation has multiple real uses, insert a cast and change all
8076 // things that used it to use the new cast. This will also hack on CI, but it
8077 // will die soon.
8078 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008079 // New is the allocation instruction, pointer typed. AI is the original
8080 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008081 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008082 AI.replaceAllUsesWith(NewCast);
8083 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008084 return ReplaceInstUsesWith(CI, New);
8085}
8086
Chris Lattner70074e02006-05-13 02:06:03 +00008087/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008088/// and return it as type Ty without inserting any new casts and without
8089/// changing the computed value. This is used by code that tries to decide
8090/// whether promoting or shrinking integer operations to wider or smaller types
8091/// will allow us to eliminate a truncate or extend.
8092///
8093/// This is a truncation operation if Ty is smaller than V->getType(), or an
8094/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008095///
8096/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8097/// should return true if trunc(V) can be computed by computing V in the smaller
8098/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8099/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8100/// efficiently truncated.
8101///
8102/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8103/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8104/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008105bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008106 unsigned CastOpc,
8107 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008108 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008109 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008110 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008111
8112 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008113 if (!I) return false;
8114
Dan Gohman6de29f82009-06-15 22:12:54 +00008115 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008116
Chris Lattner951626b2007-08-02 06:11:14 +00008117 // If this is an extension or truncate, we can often eliminate it.
8118 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8119 // If this is a cast from the destination type, we can trivially eliminate
8120 // it, and this will remove a cast overall.
8121 if (I->getOperand(0)->getType() == Ty) {
8122 // If the first operand is itself a cast, and is eliminable, do not count
8123 // this as an eliminable cast. We would prefer to eliminate those two
8124 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008125 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008126 ++NumCastsRemoved;
8127 return true;
8128 }
8129 }
8130
8131 // We can't extend or shrink something that has multiple uses: doing so would
8132 // require duplicating the instruction in general, which isn't profitable.
8133 if (!I->hasOneUse()) return false;
8134
Evan Chengf35fd542009-01-15 17:01:23 +00008135 unsigned Opc = I->getOpcode();
8136 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008137 case Instruction::Add:
8138 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008139 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008140 case Instruction::And:
8141 case Instruction::Or:
8142 case Instruction::Xor:
8143 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008144 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008145 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008146 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008147 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008148
Eli Friedman070a9812009-07-13 22:46:01 +00008149 case Instruction::UDiv:
8150 case Instruction::URem: {
8151 // UDiv and URem can be truncated if all the truncated bits are zero.
8152 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8153 uint32_t BitWidth = Ty->getScalarSizeInBits();
8154 if (BitWidth < OrigBitWidth) {
8155 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8156 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8157 MaskedValueIsZero(I->getOperand(1), Mask)) {
8158 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8159 NumCastsRemoved) &&
8160 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8161 NumCastsRemoved);
8162 }
8163 }
8164 break;
8165 }
Chris Lattner46b96052006-11-29 07:18:39 +00008166 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008167 // If we are truncating the result of this SHL, and if it's a shift of a
8168 // constant amount, we can always perform a SHL in a smaller type.
8169 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008170 uint32_t BitWidth = Ty->getScalarSizeInBits();
8171 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008172 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008173 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008174 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008175 }
8176 break;
8177 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008178 // If this is a truncate of a logical shr, we can truncate it to a smaller
8179 // lshr iff we know that the bits we would otherwise be shifting in are
8180 // already zeros.
8181 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008182 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8183 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008184 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008185 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008186 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8187 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008188 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008189 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008190 }
8191 }
Chris Lattner46b96052006-11-29 07:18:39 +00008192 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008193 case Instruction::ZExt:
8194 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008195 case Instruction::Trunc:
8196 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008197 // can safely replace it. Note that replacing it does not reduce the number
8198 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008199 if (Opc == CastOpc)
8200 return true;
8201
8202 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008203 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008204 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008205 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008206 case Instruction::Select: {
8207 SelectInst *SI = cast<SelectInst>(I);
8208 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008209 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008210 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008211 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008212 }
Chris Lattner8114b712008-06-18 04:00:49 +00008213 case Instruction::PHI: {
8214 // We can change a phi if we can change all operands.
8215 PHINode *PN = cast<PHINode>(I);
8216 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8217 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008218 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008219 return false;
8220 return true;
8221 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008222 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008223 // TODO: Can handle more cases here.
8224 break;
8225 }
8226
8227 return false;
8228}
8229
8230/// EvaluateInDifferentType - Given an expression that
8231/// CanEvaluateInDifferentType returns true for, actually insert the code to
8232/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008233Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008234 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008235 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008236 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008237
8238 // Otherwise, it must be an instruction.
8239 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008240 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008241 unsigned Opc = I->getOpcode();
8242 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008243 case Instruction::Add:
8244 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008245 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008246 case Instruction::And:
8247 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008248 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008249 case Instruction::AShr:
8250 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008251 case Instruction::Shl:
8252 case Instruction::UDiv:
8253 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008254 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008255 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008256 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008257 break;
8258 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008259 case Instruction::Trunc:
8260 case Instruction::ZExt:
8261 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008262 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008263 // just return the source. There's no need to insert it because it is not
8264 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008265 if (I->getOperand(0)->getType() == Ty)
8266 return I->getOperand(0);
8267
Chris Lattner8114b712008-06-18 04:00:49 +00008268 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008269 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008270 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008271 case Instruction::Select: {
8272 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8273 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8274 Res = SelectInst::Create(I->getOperand(0), True, False);
8275 break;
8276 }
Chris Lattner8114b712008-06-18 04:00:49 +00008277 case Instruction::PHI: {
8278 PHINode *OPN = cast<PHINode>(I);
8279 PHINode *NPN = PHINode::Create(Ty);
8280 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8281 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8282 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8283 }
8284 Res = NPN;
8285 break;
8286 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008287 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008288 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008289 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008290 break;
8291 }
8292
Chris Lattner8114b712008-06-18 04:00:49 +00008293 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008294 return InsertNewInstBefore(Res, *I);
8295}
8296
Reid Spencer3da59db2006-11-27 01:05:10 +00008297/// @brief Implement the transforms common to all CastInst visitors.
8298Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008299 Value *Src = CI.getOperand(0);
8300
Dan Gohman23d9d272007-05-11 21:10:54 +00008301 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008302 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008303 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008304 if (Instruction::CastOps opc =
8305 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8306 // The first cast (CSrc) is eliminable so we need to fix up or replace
8307 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008308 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008309 }
8310 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008311
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008313 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8314 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8315 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008316
8317 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008318 if (isa<PHINode>(Src)) {
8319 // We don't do this if this would create a PHI node with an illegal type if
8320 // it is currently legal.
8321 if (!isa<IntegerType>(Src->getType()) ||
8322 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008323 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008324 if (Instruction *NV = FoldOpIntoPhi(CI))
8325 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008326 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008327
Reid Spencer3da59db2006-11-27 01:05:10 +00008328 return 0;
8329}
8330
Chris Lattner46cd5a12009-01-09 05:44:56 +00008331/// FindElementAtOffset - Given a type and a constant offset, determine whether
8332/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008333/// the specified offset. If so, fill them into NewIndices and return the
8334/// resultant element type, otherwise return null.
8335static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8336 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008337 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008338 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008339 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008340 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008341
8342 // Start with the index over the outer type. Note that the type size
8343 // might be zero (even if the offset isn't zero) if the indexed type
8344 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008345 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008346 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008347 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008348 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008349 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008350
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008351 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008352 if (Offset < 0) {
8353 --FirstIdx;
8354 Offset += TySize;
8355 assert(Offset >= 0);
8356 }
8357 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8358 }
8359
Owen Andersoneed707b2009-07-24 23:12:02 +00008360 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008361
8362 // Index into the types. If we fail, set OrigBase to null.
8363 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008364 // Indexing into tail padding between struct/array elements.
8365 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008366 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008367
Chris Lattner46cd5a12009-01-09 05:44:56 +00008368 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8369 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008370 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8371 "Offset must stay within the indexed type");
8372
Chris Lattner46cd5a12009-01-09 05:44:56 +00008373 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008374 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008375
8376 Offset -= SL->getElementOffset(Elt);
8377 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008378 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008379 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008380 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008381 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008382 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008383 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008384 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008385 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008386 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008387 }
8388 }
8389
Chris Lattner3914f722009-01-24 01:00:13 +00008390 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008391}
8392
Chris Lattnerd3e28342007-04-27 17:44:50 +00008393/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8394Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8395 Value *Src = CI.getOperand(0);
8396
Chris Lattnerd3e28342007-04-27 17:44:50 +00008397 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008398 // If casting the result of a getelementptr instruction with no offset, turn
8399 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008400 if (GEP->hasAllZeroIndices()) {
8401 // Changing the cast operand is usually not a good idea but it is safe
8402 // here because the pointer operand is being replaced with another
8403 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008404 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008405 CI.setOperand(0, GEP->getOperand(0));
8406 return &CI;
8407 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008408
8409 // If the GEP has a single use, and the base pointer is a bitcast, and the
8410 // GEP computes a constant offset, see if we can convert these three
8411 // instructions into fewer. This typically happens with unions and other
8412 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008413 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008414 if (GEP->hasAllConstantIndices()) {
8415 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008416 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008417 int64_t Offset = OffsetV->getSExtValue();
8418
8419 // Get the base pointer input of the bitcast, and the type it points to.
8420 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8421 const Type *GEPIdxTy =
8422 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008423 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008424 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008425 // If we were able to index down into an element, create the GEP
8426 // and bitcast the result. This eliminates one bitcast, potentially
8427 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008428 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8429 Builder->CreateInBoundsGEP(OrigBase,
8430 NewIndices.begin(), NewIndices.end()) :
8431 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008432 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008433
Chris Lattner46cd5a12009-01-09 05:44:56 +00008434 if (isa<BitCastInst>(CI))
8435 return new BitCastInst(NGEP, CI.getType());
8436 assert(isa<PtrToIntInst>(CI));
8437 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008438 }
8439 }
8440 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008441 }
8442
8443 return commonCastTransforms(CI);
8444}
8445
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008446/// commonIntCastTransforms - This function implements the common transforms
8447/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008448Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8449 if (Instruction *Result = commonCastTransforms(CI))
8450 return Result;
8451
8452 Value *Src = CI.getOperand(0);
8453 const Type *SrcTy = Src->getType();
8454 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008455 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8456 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008457
Reid Spencer3da59db2006-11-27 01:05:10 +00008458 // See if we can simplify any instructions used by the LHS whose sole
8459 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008460 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008461 return &CI;
8462
8463 // If the source isn't an instruction or has more than one use then we
8464 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008465 Instruction *SrcI = dyn_cast<Instruction>(Src);
8466 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008467 return 0;
8468
Chris Lattnerc739cd62007-03-03 05:27:34 +00008469 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008470 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008471 // Only do this if the dest type is a simple type, don't convert the
8472 // expression tree to something weird like i93 unless the source is also
8473 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008474 if ((isa<VectorType>(DestTy) ||
8475 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8476 CanEvaluateInDifferentType(SrcI, DestTy,
8477 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008478 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008479 // eliminates the cast, so it is always a win. If this is a zero-extension,
8480 // we need to do an AND to maintain the clear top-part of the computation,
8481 // so we require that the input have eliminated at least one cast. If this
8482 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008483 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008484 bool DoXForm = false;
8485 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008486 switch (CI.getOpcode()) {
8487 default:
8488 // All the others use floating point so we shouldn't actually
8489 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008490 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008491 case Instruction::Trunc:
8492 DoXForm = true;
8493 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008494 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008495 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008496
Chris Lattner39c27ed2009-01-31 19:05:27 +00008497 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008498 // If it's unnecessary to issue an AND to clear the high bits, it's
8499 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008500 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008501 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8502 if (MaskedValueIsZero(TryRes, Mask))
8503 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008504
8505 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008506 if (TryI->use_empty())
8507 EraseInstFromFunction(*TryI);
8508 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008509 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008510 }
Evan Chengf35fd542009-01-15 17:01:23 +00008511 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008512 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008513 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008514 // If we do not have to emit the truncate + sext pair, then it's always
8515 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008516 //
8517 // It's not safe to eliminate the trunc + sext pair if one of the
8518 // eliminated cast is a truncate. e.g.
8519 // t2 = trunc i32 t1 to i16
8520 // t3 = sext i16 t2 to i32
8521 // !=
8522 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008523 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008524 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8525 if (NumSignBits > (DestBitSize - SrcBitSize))
8526 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008527
8528 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008529 if (TryI->use_empty())
8530 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008531 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008532 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008533 }
Evan Chengf35fd542009-01-15 17:01:23 +00008534 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008535
8536 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008537 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8538 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008539 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8540 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008541 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008542 // Just replace this cast with the result.
8543 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008544
Reid Spencer3da59db2006-11-27 01:05:10 +00008545 assert(Res->getType() == DestTy);
8546 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008547 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008548 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008549 // Just replace this cast with the result.
8550 return ReplaceInstUsesWith(CI, Res);
8551 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008552 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008553
8554 // If the high bits are already zero, just replace this cast with the
8555 // result.
8556 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8557 if (MaskedValueIsZero(Res, Mask))
8558 return ReplaceInstUsesWith(CI, Res);
8559
8560 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008561 Constant *C = ConstantInt::get(*Context,
8562 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008563 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008564 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008565 case Instruction::SExt: {
8566 // If the high bits are already filled with sign bit, just replace this
8567 // cast with the result.
8568 unsigned NumSignBits = ComputeNumSignBits(Res);
8569 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008570 return ReplaceInstUsesWith(CI, Res);
8571
Reid Spencer3da59db2006-11-27 01:05:10 +00008572 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008573 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008574 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008575 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008576 }
8577 }
8578
8579 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8580 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8581
8582 switch (SrcI->getOpcode()) {
8583 case Instruction::Add:
8584 case Instruction::Mul:
8585 case Instruction::And:
8586 case Instruction::Or:
8587 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008588 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008589 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8590 // Don't insert two casts unless at least one can be eliminated.
8591 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008592 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008593 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8594 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008595 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008596 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008597 }
8598 }
8599
8600 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8601 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8602 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008603 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008604 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008605 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008606 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008607 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008608 }
8609 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008610
Eli Friedman65445c52009-07-13 21:45:57 +00008611 case Instruction::Shl: {
8612 // Canonicalize trunc inside shl, if we can.
8613 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8614 if (CI && DestBitSize < SrcBitSize &&
8615 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008616 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8617 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008618 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008619 }
8620 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008621 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008622 }
8623 return 0;
8624}
8625
Chris Lattner8a9f5712007-04-11 06:57:46 +00008626Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008627 if (Instruction *Result = commonIntCastTransforms(CI))
8628 return Result;
8629
8630 Value *Src = CI.getOperand(0);
8631 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008632 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8633 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008634
8635 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008636 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008637 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008638 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008639 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008640 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008641 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008642
Chris Lattner4f9797d2009-03-24 18:15:30 +00008643 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8644 ConstantInt *ShAmtV = 0;
8645 Value *ShiftOp = 0;
8646 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008647 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008648 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8649
8650 // Get a mask for the bits shifting in.
8651 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8652 if (MaskedValueIsZero(ShiftOp, Mask)) {
8653 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008654 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008655
8656 // Okay, we can shrink this. Truncate the input, then return a new
8657 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008658 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008659 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008660 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008661 }
8662 }
Chris Lattner9956c052009-11-08 19:23:30 +00008663
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008664 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008665}
8666
Evan Chengb98a10e2008-03-24 00:21:34 +00008667/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8668/// in order to eliminate the icmp.
8669Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8670 bool DoXform) {
8671 // If we are just checking for a icmp eq of a single bit and zext'ing it
8672 // to an integer, then shift the bit to the appropriate place and then
8673 // cast to integer to avoid the comparison.
8674 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8675 const APInt &Op1CV = Op1C->getValue();
8676
8677 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8678 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8679 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8680 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8681 if (!DoXform) return ICI;
8682
8683 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008684 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008685 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008686 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008687 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008688 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008689
8690 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008691 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008692 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008693 }
8694
8695 return ReplaceInstUsesWith(CI, In);
8696 }
8697
8698
8699
8700 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8701 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8702 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8703 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8704 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8705 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8706 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8707 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8708 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8709 // This only works for EQ and NE
8710 ICI->isEquality()) {
8711 // If Op1C some other power of two, convert:
8712 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8713 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8714 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8715 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8716
8717 APInt KnownZeroMask(~KnownZero);
8718 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8719 if (!DoXform) return ICI;
8720
8721 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8722 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8723 // (X&4) == 2 --> false
8724 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008725 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008726 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008727 return ReplaceInstUsesWith(CI, Res);
8728 }
8729
8730 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8731 Value *In = ICI->getOperand(0);
8732 if (ShiftAmt) {
8733 // Perform a logical shr by shiftamt.
8734 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008735 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8736 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008737 }
8738
8739 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008740 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008741 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008742 }
8743
8744 if (CI.getType() == In->getType())
8745 return ReplaceInstUsesWith(CI, In);
8746 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008747 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008748 }
8749 }
8750 }
8751
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008752 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8753 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8754 // may lead to additional simplifications.
8755 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8756 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8757 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008758 Value *LHS = ICI->getOperand(0);
8759 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008760
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008761 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8762 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8763 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8764 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8765 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008766
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008767 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8768 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8769 APInt UnknownBit = ~KnownBits;
8770 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008771 if (!DoXform) return ICI;
8772
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008773 Value *Result = Builder->CreateXor(LHS, RHS);
8774
8775 // Mask off any bits that are set and won't be shifted away.
8776 if (KnownOneLHS.uge(UnknownBit))
8777 Result = Builder->CreateAnd(Result,
8778 ConstantInt::get(ITy, UnknownBit));
8779
8780 // Shift the bit we're testing down to the lsb.
8781 Result = Builder->CreateLShr(
8782 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8783
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008784 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008785 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8786 Result->takeName(ICI);
8787 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008788 }
8789 }
8790 }
8791 }
8792
Evan Chengb98a10e2008-03-24 00:21:34 +00008793 return 0;
8794}
8795
Chris Lattner8a9f5712007-04-11 06:57:46 +00008796Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008797 // If one of the common conversion will work ..
8798 if (Instruction *Result = commonIntCastTransforms(CI))
8799 return Result;
8800
8801 Value *Src = CI.getOperand(0);
8802
Chris Lattnera84f47c2009-02-17 20:47:23 +00008803 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8804 // types and if the sizes are just right we can convert this into a logical
8805 // 'and' which will be much cheaper than the pair of casts.
8806 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8807 // Get the sizes of the types involved. We know that the intermediate type
8808 // will be smaller than A or C, but don't know the relation between A and C.
8809 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008810 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8811 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8812 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008813 // If we're actually extending zero bits, then if
8814 // SrcSize < DstSize: zext(a & mask)
8815 // SrcSize == DstSize: a & mask
8816 // SrcSize > DstSize: trunc(a) & mask
8817 if (SrcSize < DstSize) {
8818 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008819 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008820 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008821 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008822 }
8823
8824 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008825 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008826 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008827 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008828 }
8829 if (SrcSize > DstSize) {
8830 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008831 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008832 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008833 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008834 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008835 }
8836 }
8837
Evan Chengb98a10e2008-03-24 00:21:34 +00008838 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8839 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008840
Evan Chengb98a10e2008-03-24 00:21:34 +00008841 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8842 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8843 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8844 // of the (zext icmp) will be transformed.
8845 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8846 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8847 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8848 (transformZExtICmp(LHS, CI, false) ||
8849 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008850 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8851 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008852 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008853 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008854 }
8855
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008856 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008857 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8858 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8859 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8860 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008861 if (TI0->getType() == CI.getType())
8862 return
8863 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008864 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008865 }
8866
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008867 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8868 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8869 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8870 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8871 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8872 And->getOperand(1) == C)
8873 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8874 Value *TI0 = TI->getOperand(0);
8875 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008876 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008877 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008878 return BinaryOperator::CreateXor(NewAnd, ZC);
8879 }
8880 }
8881
Reid Spencer3da59db2006-11-27 01:05:10 +00008882 return 0;
8883}
8884
Chris Lattner8a9f5712007-04-11 06:57:46 +00008885Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008886 if (Instruction *I = commonIntCastTransforms(CI))
8887 return I;
8888
Chris Lattner8a9f5712007-04-11 06:57:46 +00008889 Value *Src = CI.getOperand(0);
8890
Dan Gohman1975d032008-10-30 20:40:10 +00008891 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008892 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008893 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008894 Constant::getAllOnesValue(CI.getType()),
8895 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008896
8897 // See if the value being truncated is already sign extended. If so, just
8898 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008899 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008900 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008901 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8902 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8903 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008904 unsigned NumSignBits = ComputeNumSignBits(Op);
8905
8906 if (OpBits == DestBits) {
8907 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8908 // bits, it is already ready.
8909 if (NumSignBits > DestBits-MidBits)
8910 return ReplaceInstUsesWith(CI, Op);
8911 } else if (OpBits < DestBits) {
8912 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8913 // bits, just sext from i32.
8914 if (NumSignBits > OpBits-MidBits)
8915 return new SExtInst(Op, CI.getType(), "tmp");
8916 } else {
8917 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8918 // bits, just truncate to i32.
8919 if (NumSignBits > OpBits-MidBits)
8920 return new TruncInst(Op, CI.getType(), "tmp");
8921 }
8922 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008923
8924 // If the input is a shl/ashr pair of a same constant, then this is a sign
8925 // extension from a smaller value. If we could trust arbitrary bitwidth
8926 // integers, we could turn this into a truncate to the smaller bit and then
8927 // use a sext for the whole extension. Since we don't, look deeper and check
8928 // for a truncate. If the source and dest are the same type, eliminate the
8929 // trunc and extend and just do shifts. For example, turn:
8930 // %a = trunc i32 %i to i8
8931 // %b = shl i8 %a, 6
8932 // %c = ashr i8 %b, 6
8933 // %d = sext i8 %c to i32
8934 // into:
8935 // %a = shl i32 %i, 30
8936 // %d = ashr i32 %a, 30
8937 Value *A = 0;
8938 ConstantInt *BA = 0, *CA = 0;
8939 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008940 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008941 BA == CA && isa<TruncInst>(A)) {
8942 Value *I = cast<TruncInst>(A)->getOperand(0);
8943 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008944 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8945 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008946 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008947 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008948 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008949 return BinaryOperator::CreateAShr(I, ShAmtV);
8950 }
8951 }
8952
Chris Lattnerba417832007-04-11 06:12:58 +00008953 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008954}
8955
Chris Lattnerb7530652008-01-27 05:29:54 +00008956/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8957/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008958static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008959 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008960 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008961 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008962 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8963 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008964 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008965 return 0;
8966}
8967
8968/// LookThroughFPExtensions - If this is an fp extension instruction, look
8969/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008970static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008971 if (Instruction *I = dyn_cast<Instruction>(V))
8972 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008973 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008974
8975 // If this value is a constant, return the constant in the smallest FP type
8976 // that can accurately represent it. This allows us to turn
8977 // (float)((double)X+2.0) into x+2.0f.
8978 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008979 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008980 return V; // No constant folding of this.
8981 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008982 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008983 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008984 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008985 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008986 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008987 return V;
8988 // Don't try to shrink to various long double types.
8989 }
8990
8991 return V;
8992}
8993
8994Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8995 if (Instruction *I = commonCastTransforms(CI))
8996 return I;
8997
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008998 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008999 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009000 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00009001 // many builtins (sqrt, etc).
9002 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9003 if (OpI && OpI->hasOneUse()) {
9004 switch (OpI->getOpcode()) {
9005 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009006 case Instruction::FAdd:
9007 case Instruction::FSub:
9008 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00009009 case Instruction::FDiv:
9010 case Instruction::FRem:
9011 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00009012 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9013 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009014 if (LHSTrunc->getType() != SrcTy &&
9015 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009016 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00009017 // If the source types were both smaller than the destination type of
9018 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00009019 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9020 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009021 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9022 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009023 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00009024 }
9025 }
9026 break;
9027 }
9028 }
9029 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009030}
9031
9032Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9033 return commonCastTransforms(CI);
9034}
9035
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009036Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009037 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9038 if (OpI == 0)
9039 return commonCastTransforms(FI);
9040
9041 // fptoui(uitofp(X)) --> X
9042 // fptoui(sitofp(X)) --> X
9043 // This is safe if the intermediate type has enough bits in its mantissa to
9044 // accurately represent all values of X. For example, do not do this with
9045 // i64->float->i64. This is also safe for sitofp case, because any negative
9046 // 'X' value would cause an undefined result for the fptoui.
9047 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9048 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009049 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009050 OpI->getType()->getFPMantissaWidth())
9051 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009052
9053 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009054}
9055
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009056Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009057 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9058 if (OpI == 0)
9059 return commonCastTransforms(FI);
9060
9061 // fptosi(sitofp(X)) --> X
9062 // fptosi(uitofp(X)) --> X
9063 // This is safe if the intermediate type has enough bits in its mantissa to
9064 // accurately represent all values of X. For example, do not do this with
9065 // i64->float->i64. This is also safe for sitofp case, because any negative
9066 // 'X' value would cause an undefined result for the fptoui.
9067 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9068 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009069 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009070 OpI->getType()->getFPMantissaWidth())
9071 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009072
9073 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009074}
9075
9076Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9077 return commonCastTransforms(CI);
9078}
9079
9080Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9081 return commonCastTransforms(CI);
9082}
9083
Chris Lattnera0e69692009-03-24 18:35:40 +00009084Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9085 // If the destination integer type is smaller than the intptr_t type for
9086 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9087 // trunc to be exposed to other transforms. Don't do this for extending
9088 // ptrtoint's, because we don't know if the target sign or zero extends its
9089 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009090 if (TD &&
9091 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009092 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9093 TD->getIntPtrType(CI.getContext()),
9094 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009095 return new TruncInst(P, CI.getType());
9096 }
9097
Chris Lattnerd3e28342007-04-27 17:44:50 +00009098 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009099}
9100
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009101Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009102 // If the source integer type is larger than the intptr_t type for
9103 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9104 // allows the trunc to be exposed to other transforms. Don't do this for
9105 // extending inttoptr's, because we don't know if the target sign or zero
9106 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009107 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009108 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009109 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9110 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009111 return new IntToPtrInst(P, CI.getType());
9112 }
9113
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009114 if (Instruction *I = commonCastTransforms(CI))
9115 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009116
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009117 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009118}
9119
Chris Lattnerd3e28342007-04-27 17:44:50 +00009120Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009121 // If the operands are integer typed then apply the integer transforms,
9122 // otherwise just apply the common ones.
9123 Value *Src = CI.getOperand(0);
9124 const Type *SrcTy = Src->getType();
9125 const Type *DestTy = CI.getType();
9126
Eli Friedman7e25d452009-07-13 20:53:00 +00009127 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009128 if (Instruction *I = commonPointerCastTransforms(CI))
9129 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009130 } else {
9131 if (Instruction *Result = commonCastTransforms(CI))
9132 return Result;
9133 }
9134
9135
9136 // Get rid of casts from one type to the same type. These are useless and can
9137 // be replaced by the operand.
9138 if (DestTy == Src->getType())
9139 return ReplaceInstUsesWith(CI, Src);
9140
Reid Spencer3da59db2006-11-27 01:05:10 +00009141 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009142 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9143 const Type *DstElTy = DstPTy->getElementType();
9144 const Type *SrcElTy = SrcPTy->getElementType();
9145
Nate Begeman83ad90a2008-03-31 00:22:16 +00009146 // If the address spaces don't match, don't eliminate the bitcast, which is
9147 // required for changing types.
9148 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9149 return 0;
9150
Victor Hernandez83d63912009-09-18 22:35:49 +00009151 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009152 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009153 // There is no need to modify malloc calls because it is their bitcast that
9154 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009155 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009156 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9157 return V;
9158
Chris Lattnerd717c182007-05-05 22:32:24 +00009159 // If the source and destination are pointers, and this cast is equivalent
9160 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009161 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009162 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009163 unsigned NumZeros = 0;
9164 while (SrcElTy != DstElTy &&
9165 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9166 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9167 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9168 ++NumZeros;
9169 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009170
Chris Lattnerd3e28342007-04-27 17:44:50 +00009171 // If we found a path from the src to dest, create the getelementptr now.
9172 if (SrcElTy == DstElTy) {
9173 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009174 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9175 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009176 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009177 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009178
Eli Friedman2451a642009-07-18 23:06:53 +00009179 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9180 if (DestVTy->getNumElements() == 1) {
9181 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009182 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009183 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009184 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009185 }
9186 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9187 }
9188 }
9189
9190 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9191 if (SrcVTy->getNumElements() == 1) {
9192 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009193 Value *Elem =
9194 Builder->CreateExtractElement(Src,
9195 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009196 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9197 }
9198 }
9199 }
9200
Reid Spencer3da59db2006-11-27 01:05:10 +00009201 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9202 if (SVI->hasOneUse()) {
9203 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9204 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009205 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009206 cast<VectorType>(DestTy)->getNumElements() ==
9207 SVI->getType()->getNumElements() &&
9208 SVI->getType()->getNumElements() ==
9209 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009210 CastInst *Tmp;
9211 // If either of the operands is a cast from CI.getType(), then
9212 // evaluating the shuffle in the casted destination's type will allow
9213 // us to eliminate at least one cast.
9214 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9215 Tmp->getOperand(0)->getType() == DestTy) ||
9216 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9217 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009218 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9219 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009220 // Return a new shuffle vector. Use the same element ID's, as we
9221 // know the vector types match #elts.
9222 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009223 }
9224 }
9225 }
9226 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009227 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009228}
9229
Chris Lattnere576b912004-04-09 23:46:01 +00009230/// GetSelectFoldableOperands - We want to turn code that looks like this:
9231/// %C = or %A, %B
9232/// %D = select %cond, %C, %A
9233/// into:
9234/// %C = select %cond, %B, 0
9235/// %D = or %A, %C
9236///
9237/// Assuming that the specified instruction is an operand to the select, return
9238/// a bitmask indicating which operands of this instruction are foldable if they
9239/// equal the other incoming value of the select.
9240///
9241static unsigned GetSelectFoldableOperands(Instruction *I) {
9242 switch (I->getOpcode()) {
9243 case Instruction::Add:
9244 case Instruction::Mul:
9245 case Instruction::And:
9246 case Instruction::Or:
9247 case Instruction::Xor:
9248 return 3; // Can fold through either operand.
9249 case Instruction::Sub: // Can only fold on the amount subtracted.
9250 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009251 case Instruction::LShr:
9252 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009253 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009254 default:
9255 return 0; // Cannot fold
9256 }
9257}
9258
9259/// GetSelectFoldableConstant - For the same transformation as the previous
9260/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009261static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009262 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009263 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009264 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009265 case Instruction::Add:
9266 case Instruction::Sub:
9267 case Instruction::Or:
9268 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009269 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009270 case Instruction::LShr:
9271 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009272 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009273 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009274 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009275 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009276 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009277 }
9278}
9279
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009280/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9281/// have the same opcode and only one use each. Try to simplify this.
9282Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9283 Instruction *FI) {
9284 if (TI->getNumOperands() == 1) {
9285 // If this is a non-volatile load or a cast from the same type,
9286 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009287 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009288 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9289 return 0;
9290 } else {
9291 return 0; // unknown unary op.
9292 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009293
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009294 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009295 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009296 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009297 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009298 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009299 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009300 }
9301
Reid Spencer832254e2007-02-02 02:16:23 +00009302 // Only handle binary operators here.
9303 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009304 return 0;
9305
9306 // Figure out if the operations have any operands in common.
9307 Value *MatchOp, *OtherOpT, *OtherOpF;
9308 bool MatchIsOpZero;
9309 if (TI->getOperand(0) == FI->getOperand(0)) {
9310 MatchOp = TI->getOperand(0);
9311 OtherOpT = TI->getOperand(1);
9312 OtherOpF = FI->getOperand(1);
9313 MatchIsOpZero = true;
9314 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9315 MatchOp = TI->getOperand(1);
9316 OtherOpT = TI->getOperand(0);
9317 OtherOpF = FI->getOperand(0);
9318 MatchIsOpZero = false;
9319 } else if (!TI->isCommutative()) {
9320 return 0;
9321 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9322 MatchOp = TI->getOperand(0);
9323 OtherOpT = TI->getOperand(1);
9324 OtherOpF = FI->getOperand(0);
9325 MatchIsOpZero = true;
9326 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9327 MatchOp = TI->getOperand(1);
9328 OtherOpT = TI->getOperand(0);
9329 OtherOpF = FI->getOperand(1);
9330 MatchIsOpZero = true;
9331 } else {
9332 return 0;
9333 }
9334
9335 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009336 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9337 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009338 InsertNewInstBefore(NewSI, SI);
9339
9340 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9341 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009342 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009343 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009344 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009345 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009346 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009347 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009348}
9349
Evan Chengde621922009-03-31 20:42:45 +00009350static bool isSelect01(Constant *C1, Constant *C2) {
9351 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9352 if (!C1I)
9353 return false;
9354 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9355 if (!C2I)
9356 return false;
9357 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9358}
9359
9360/// FoldSelectIntoOp - Try fold the select into one of the operands to
9361/// facilitate further optimization.
9362Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9363 Value *FalseVal) {
9364 // See the comment above GetSelectFoldableOperands for a description of the
9365 // transformation we are doing here.
9366 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9367 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9368 !isa<Constant>(FalseVal)) {
9369 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9370 unsigned OpToFold = 0;
9371 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9372 OpToFold = 1;
9373 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9374 OpToFold = 2;
9375 }
9376
9377 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009378 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009379 Value *OOp = TVI->getOperand(2-OpToFold);
9380 // Avoid creating select between 2 constants unless it's selecting
9381 // between 0 and 1.
9382 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9383 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9384 InsertNewInstBefore(NewSel, SI);
9385 NewSel->takeName(TVI);
9386 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9387 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009388 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009389 }
9390 }
9391 }
9392 }
9393 }
9394
9395 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9396 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9397 !isa<Constant>(TrueVal)) {
9398 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9399 unsigned OpToFold = 0;
9400 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9401 OpToFold = 1;
9402 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9403 OpToFold = 2;
9404 }
9405
9406 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009407 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009408 Value *OOp = FVI->getOperand(2-OpToFold);
9409 // Avoid creating select between 2 constants unless it's selecting
9410 // between 0 and 1.
9411 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9412 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9413 InsertNewInstBefore(NewSel, SI);
9414 NewSel->takeName(FVI);
9415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9416 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009417 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009418 }
9419 }
9420 }
9421 }
9422 }
9423
9424 return 0;
9425}
9426
Dan Gohman81b28ce2008-09-16 18:46:06 +00009427/// visitSelectInstWithICmp - Visit a SelectInst that has an
9428/// ICmpInst as its first operand.
9429///
9430Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9431 ICmpInst *ICI) {
9432 bool Changed = false;
9433 ICmpInst::Predicate Pred = ICI->getPredicate();
9434 Value *CmpLHS = ICI->getOperand(0);
9435 Value *CmpRHS = ICI->getOperand(1);
9436 Value *TrueVal = SI.getTrueValue();
9437 Value *FalseVal = SI.getFalseValue();
9438
9439 // Check cases where the comparison is with a constant that
9440 // can be adjusted to fit the min/max idiom. We may edit ICI in
9441 // place here, so make sure the select is the only user.
9442 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009443 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009444 switch (Pred) {
9445 default: break;
9446 case ICmpInst::ICMP_ULT:
9447 case ICmpInst::ICMP_SLT: {
9448 // X < MIN ? T : F --> F
9449 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9450 return ReplaceInstUsesWith(SI, FalseVal);
9451 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009452 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009453 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9454 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9455 Pred = ICmpInst::getSwappedPredicate(Pred);
9456 CmpRHS = AdjustedRHS;
9457 std::swap(FalseVal, TrueVal);
9458 ICI->setPredicate(Pred);
9459 ICI->setOperand(1, CmpRHS);
9460 SI.setOperand(1, TrueVal);
9461 SI.setOperand(2, FalseVal);
9462 Changed = true;
9463 }
9464 break;
9465 }
9466 case ICmpInst::ICMP_UGT:
9467 case ICmpInst::ICMP_SGT: {
9468 // X > MAX ? T : F --> F
9469 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9470 return ReplaceInstUsesWith(SI, FalseVal);
9471 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009472 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009473 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9474 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9475 Pred = ICmpInst::getSwappedPredicate(Pred);
9476 CmpRHS = AdjustedRHS;
9477 std::swap(FalseVal, TrueVal);
9478 ICI->setPredicate(Pred);
9479 ICI->setOperand(1, CmpRHS);
9480 SI.setOperand(1, TrueVal);
9481 SI.setOperand(2, FalseVal);
9482 Changed = true;
9483 }
9484 break;
9485 }
9486 }
9487
Dan Gohman1975d032008-10-30 20:40:10 +00009488 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9489 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009490 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009491 if (match(TrueVal, m_ConstantInt<-1>()) &&
9492 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009493 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009494 else if (match(TrueVal, m_ConstantInt<0>()) &&
9495 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009496 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9497
Dan Gohman1975d032008-10-30 20:40:10 +00009498 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9499 // If we are just checking for a icmp eq of a single bit and zext'ing it
9500 // to an integer, then shift the bit to the appropriate place and then
9501 // cast to integer to avoid the comparison.
9502 const APInt &Op1CV = CI->getValue();
9503
9504 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9505 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9506 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009507 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009508 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009509 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009510 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009511 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009512 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009513 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009514 if (In->getType() != SI.getType())
9515 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009516 true/*SExt*/, "tmp", ICI);
9517
9518 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009519 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009520 In->getName()+".not"), *ICI);
9521
9522 return ReplaceInstUsesWith(SI, In);
9523 }
9524 }
9525 }
9526
Dan Gohman81b28ce2008-09-16 18:46:06 +00009527 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9528 // Transform (X == Y) ? X : Y -> Y
9529 if (Pred == ICmpInst::ICMP_EQ)
9530 return ReplaceInstUsesWith(SI, FalseVal);
9531 // Transform (X != Y) ? X : Y -> X
9532 if (Pred == ICmpInst::ICMP_NE)
9533 return ReplaceInstUsesWith(SI, TrueVal);
9534 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9535
9536 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9537 // Transform (X == Y) ? Y : X -> X
9538 if (Pred == ICmpInst::ICMP_EQ)
9539 return ReplaceInstUsesWith(SI, FalseVal);
9540 // Transform (X != Y) ? Y : X -> Y
9541 if (Pred == ICmpInst::ICMP_NE)
9542 return ReplaceInstUsesWith(SI, TrueVal);
9543 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9544 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009545 return Changed ? &SI : 0;
9546}
9547
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009548
Chris Lattner7f239582009-10-22 00:17:26 +00009549/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9550/// PHI node (but the two may be in different blocks). See if the true/false
9551/// values (V) are live in all of the predecessor blocks of the PHI. For
9552/// example, cases like this cannot be mapped:
9553///
9554/// X = phi [ C1, BB1], [C2, BB2]
9555/// Y = add
9556/// Z = select X, Y, 0
9557///
9558/// because Y is not live in BB1/BB2.
9559///
9560static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9561 const SelectInst &SI) {
9562 // If the value is a non-instruction value like a constant or argument, it
9563 // can always be mapped.
9564 const Instruction *I = dyn_cast<Instruction>(V);
9565 if (I == 0) return true;
9566
9567 // If V is a PHI node defined in the same block as the condition PHI, we can
9568 // map the arguments.
9569 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9570
9571 if (const PHINode *VP = dyn_cast<PHINode>(I))
9572 if (VP->getParent() == CondPHI->getParent())
9573 return true;
9574
9575 // Otherwise, if the PHI and select are defined in the same block and if V is
9576 // defined in a different block, then we can transform it.
9577 if (SI.getParent() == CondPHI->getParent() &&
9578 I->getParent() != CondPHI->getParent())
9579 return true;
9580
9581 // Otherwise we have a 'hard' case and we can't tell without doing more
9582 // detailed dominator based analysis, punt.
9583 return false;
9584}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009585
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009586/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9587/// SPF2(SPF1(A, B), C)
9588Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9589 SelectPatternFlavor SPF1,
9590 Value *A, Value *B,
9591 Instruction &Outer,
9592 SelectPatternFlavor SPF2, Value *C) {
9593 if (C == A || C == B) {
9594 // MAX(MAX(A, B), B) -> MAX(A, B)
9595 // MIN(MIN(a, b), a) -> MIN(a, b)
9596 if (SPF1 == SPF2)
9597 return ReplaceInstUsesWith(Outer, Inner);
9598
9599 // MAX(MIN(a, b), a) -> a
9600 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009601 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9602 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9603 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9604 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009605 return ReplaceInstUsesWith(Outer, C);
9606 }
9607
9608 // TODO: MIN(MIN(A, 23), 97)
9609 return 0;
9610}
9611
9612
9613
9614
Chris Lattner3d69f462004-03-12 05:52:32 +00009615Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009616 Value *CondVal = SI.getCondition();
9617 Value *TrueVal = SI.getTrueValue();
9618 Value *FalseVal = SI.getFalseValue();
9619
9620 // select true, X, Y -> X
9621 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009622 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009623 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009624
9625 // select C, X, X -> X
9626 if (TrueVal == FalseVal)
9627 return ReplaceInstUsesWith(SI, TrueVal);
9628
Chris Lattnere87597f2004-10-16 18:11:37 +00009629 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9630 return ReplaceInstUsesWith(SI, FalseVal);
9631 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9632 return ReplaceInstUsesWith(SI, TrueVal);
9633 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9634 if (isa<Constant>(TrueVal))
9635 return ReplaceInstUsesWith(SI, TrueVal);
9636 else
9637 return ReplaceInstUsesWith(SI, FalseVal);
9638 }
9639
Owen Anderson1d0be152009-08-13 21:58:54 +00009640 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009641 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009642 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009643 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009644 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009645 } else {
9646 // Change: A = select B, false, C --> A = and !B, C
9647 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009648 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009649 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009650 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009651 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009652 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009653 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009654 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009655 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009656 } else {
9657 // Change: A = select B, C, true --> A = or !B, C
9658 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009659 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009660 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009661 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009662 }
9663 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009664
9665 // select a, b, a -> a&b
9666 // select a, a, b -> a|b
9667 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009668 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009669 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009670 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009671 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009672
Chris Lattner2eefe512004-04-09 19:05:30 +00009673 // Selecting between two integer constants?
9674 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9675 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009676 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009677 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009678 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009679 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009680 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009681 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009682 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009683 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009684 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009685 }
Chris Lattner457dd822004-06-09 07:59:58 +00009686
Reid Spencere4d87aa2006-12-23 06:05:41 +00009687 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009688 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009689 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009690 // non-constant value, eliminate this whole mess. This corresponds to
9691 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009692 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009693 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009694 cast<Constant>(IC->getOperand(1))->isNullValue())
9695 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9696 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009697 isa<ConstantInt>(ICA->getOperand(1)) &&
9698 (ICA->getOperand(1) == TrueValC ||
9699 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009700 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9701 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009702 // know whether we have a icmp_ne or icmp_eq and whether the
9703 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009704 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009705 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009706 Value *V = ICA;
9707 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009708 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009709 Instruction::Xor, V, ICA->getOperand(1)), SI);
9710 return ReplaceInstUsesWith(SI, V);
9711 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009712 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009713 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009714
9715 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009716 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9717 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009718 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009719 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9720 // This is not safe in general for floating point:
9721 // consider X== -0, Y== +0.
9722 // It becomes safe if either operand is a nonzero constant.
9723 ConstantFP *CFPt, *CFPf;
9724 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9725 !CFPt->getValueAPF().isZero()) ||
9726 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9727 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009728 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009729 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009730 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009731 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009732 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009733 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009734
Reid Spencere4d87aa2006-12-23 06:05:41 +00009735 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009736 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009737 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9738 // This is not safe in general for floating point:
9739 // consider X== -0, Y== +0.
9740 // It becomes safe if either operand is a nonzero constant.
9741 ConstantFP *CFPt, *CFPf;
9742 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9743 !CFPt->getValueAPF().isZero()) ||
9744 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9745 !CFPf->getValueAPF().isZero()))
9746 return ReplaceInstUsesWith(SI, FalseVal);
9747 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009748 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009749 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9750 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009751 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009752 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009753 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009754 }
9755
9756 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009757 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9758 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9759 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009760
Chris Lattner87875da2005-01-13 22:52:24 +00009761 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9762 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9763 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009764 Instruction *AddOp = 0, *SubOp = 0;
9765
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009766 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9767 if (TI->getOpcode() == FI->getOpcode())
9768 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9769 return IV;
9770
9771 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9772 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009773 if ((TI->getOpcode() == Instruction::Sub &&
9774 FI->getOpcode() == Instruction::Add) ||
9775 (TI->getOpcode() == Instruction::FSub &&
9776 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009777 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009778 } else if ((FI->getOpcode() == Instruction::Sub &&
9779 TI->getOpcode() == Instruction::Add) ||
9780 (FI->getOpcode() == Instruction::FSub &&
9781 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009782 AddOp = TI; SubOp = FI;
9783 }
9784
9785 if (AddOp) {
9786 Value *OtherAddOp = 0;
9787 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9788 OtherAddOp = AddOp->getOperand(1);
9789 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9790 OtherAddOp = AddOp->getOperand(0);
9791 }
9792
9793 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009794 // So at this point we know we have (Y -> OtherAddOp):
9795 // select C, (add X, Y), (sub X, Z)
9796 Value *NegVal; // Compute -Z
9797 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009798 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009799 } else {
9800 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009801 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009802 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009803 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009804
9805 Value *NewTrueOp = OtherAddOp;
9806 Value *NewFalseOp = NegVal;
9807 if (AddOp != TI)
9808 std::swap(NewTrueOp, NewFalseOp);
9809 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009810 SelectInst::Create(CondVal, NewTrueOp,
9811 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009812
9813 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009814 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009815 }
9816 }
9817 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009818
Chris Lattnere576b912004-04-09 23:46:01 +00009819 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009820 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009821 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +00009822 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009823
9824 // MAX(MAX(a, b), a) -> MAX(a, b)
9825 // MIN(MIN(a, b), a) -> MIN(a, b)
9826 // MAX(MIN(a, b), a) -> a
9827 // MIN(MAX(a, b), a) -> a
9828 Value *LHS, *RHS, *LHS2, *RHS2;
9829 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
9830 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
9831 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
9832 SI, SPF, RHS))
9833 return R;
9834 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
9835 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
9836 SI, SPF, LHS))
9837 return R;
9838 }
9839
9840 // TODO.
9841 // ABS(-X) -> ABS(X)
9842 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +00009843 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009844
Chris Lattner7f239582009-10-22 00:17:26 +00009845 // See if we can fold the select into a phi node if the condition is a select.
9846 if (isa<PHINode>(SI.getCondition()))
9847 // The true/false values have to be live in the PHI predecessor's blocks.
9848 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9849 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9850 if (Instruction *NV = FoldOpIntoPhi(SI))
9851 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009852
Chris Lattnera1df33c2005-04-24 07:30:14 +00009853 if (BinaryOperator::isNot(CondVal)) {
9854 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9855 SI.setOperand(1, FalseVal);
9856 SI.setOperand(2, TrueVal);
9857 return &SI;
9858 }
9859
Chris Lattner3d69f462004-03-12 05:52:32 +00009860 return 0;
9861}
9862
Dan Gohmaneee962e2008-04-10 18:43:06 +00009863/// EnforceKnownAlignment - If the specified pointer points to an object that
9864/// we control, modify the object's alignment to PrefAlign. This isn't
9865/// often possible though. If alignment is important, a more reliable approach
9866/// is to simply align all global variables and allocation instructions to
9867/// their preferred alignment from the beginning.
9868///
9869static unsigned EnforceKnownAlignment(Value *V,
9870 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009871
Dan Gohmaneee962e2008-04-10 18:43:06 +00009872 User *U = dyn_cast<User>(V);
9873 if (!U) return Align;
9874
Dan Gohmanca178902009-07-17 20:47:02 +00009875 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009876 default: break;
9877 case Instruction::BitCast:
9878 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9879 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009880 // If all indexes are zero, it is just the alignment of the base pointer.
9881 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009882 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009883 if (!isa<Constant>(*i) ||
9884 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009885 AllZeroOperands = false;
9886 break;
9887 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009888
9889 if (AllZeroOperands) {
9890 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009891 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009892 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009893 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009894 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009895 }
9896
9897 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9898 // If there is a large requested alignment and we can, bump up the alignment
9899 // of the global.
9900 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009901 if (GV->getAlignment() >= PrefAlign)
9902 Align = GV->getAlignment();
9903 else {
9904 GV->setAlignment(PrefAlign);
9905 Align = PrefAlign;
9906 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009907 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009908 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9909 // If there is a requested alignment and if this is an alloca, round up.
9910 if (AI->getAlignment() >= PrefAlign)
9911 Align = AI->getAlignment();
9912 else {
9913 AI->setAlignment(PrefAlign);
9914 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009915 }
9916 }
9917
9918 return Align;
9919}
9920
9921/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9922/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9923/// and it is more than the alignment of the ultimate object, see if we can
9924/// increase the alignment of the ultimate object, making this check succeed.
9925unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9926 unsigned PrefAlign) {
9927 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9928 sizeof(PrefAlign) * CHAR_BIT;
9929 APInt Mask = APInt::getAllOnesValue(BitWidth);
9930 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9931 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9932 unsigned TrailZ = KnownZero.countTrailingOnes();
9933 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9934
9935 if (PrefAlign > Align)
9936 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9937
9938 // We don't need to make any adjustment.
9939 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009940}
9941
Chris Lattnerf497b022008-01-13 23:50:23 +00009942Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009943 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009944 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009945 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009946 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009947
9948 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009949 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009950 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009951 return MI;
9952 }
9953
9954 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9955 // load/store.
9956 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9957 if (MemOpLength == 0) return 0;
9958
Chris Lattner37ac6082008-01-14 00:28:35 +00009959 // Source and destination pointer types are always "i8*" for intrinsic. See
9960 // if the size is something we can handle with a single primitive load/store.
9961 // A single load+store correctly handles overlapping memory in the memmove
9962 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009963 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009964 if (Size == 0) return MI; // Delete this mem transfer.
9965
9966 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009967 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009968
Chris Lattner37ac6082008-01-14 00:28:35 +00009969 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009970 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009971 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009972
9973 // Memcpy forces the use of i8* for the source and destination. That means
9974 // that if you're using memcpy to move one double around, you'll get a cast
9975 // from double* to i8*. We'd much rather use a double load+store rather than
9976 // an i64 load+store, here because this improves the odds that the source or
9977 // dest address will be promotable. See if we can find a better type than the
9978 // integer datatype.
9979 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9980 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009981 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009982 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9983 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009984 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009985 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9986 if (STy->getNumElements() == 1)
9987 SrcETy = STy->getElementType(0);
9988 else
9989 break;
9990 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9991 if (ATy->getNumElements() == 1)
9992 SrcETy = ATy->getElementType();
9993 else
9994 break;
9995 } else
9996 break;
9997 }
9998
Dan Gohman8f8e2692008-05-23 01:52:21 +00009999 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +000010000 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010001 }
10002 }
10003
10004
Chris Lattnerf497b022008-01-13 23:50:23 +000010005 // If the memcpy/memmove provides better alignment info than we can
10006 // infer, use it.
10007 SrcAlign = std::max(SrcAlign, CopyAlign);
10008 DstAlign = std::max(DstAlign, CopyAlign);
10009
Chris Lattner08142f22009-08-30 19:47:22 +000010010 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10011 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010012 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10013 InsertNewInstBefore(L, *MI);
10014 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10015
10016 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010017 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +000010018 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +000010019}
Chris Lattner3d69f462004-03-12 05:52:32 +000010020
Chris Lattner69ea9d22008-04-30 06:39:11 +000010021Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10022 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010023 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010024 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010025 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010026 return MI;
10027 }
10028
10029 // Extract the length and alignment and fill if they are constant.
10030 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10031 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +000010032 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +000010033 return 0;
10034 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010035 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010036
10037 // If the length is zero, this is a no-op
10038 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10039
10040 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10041 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010042 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010043
10044 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010045 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010046
10047 // Alignment 0 is identity for alignment 1 for memset, but not store.
10048 if (Alignment == 0) Alignment = 1;
10049
10050 // Extract the fill value and store.
10051 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010052 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010053 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010054
10055 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010056 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010057 return MI;
10058 }
10059
10060 return 0;
10061}
10062
10063
Chris Lattner8b0ea312006-01-13 20:11:04 +000010064/// visitCallInst - CallInst simplification. This mostly only handles folding
10065/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10066/// the heavy lifting.
10067///
Chris Lattner9fe38862003-06-19 17:00:31 +000010068Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010069 if (isFreeCall(&CI))
10070 return visitFree(CI);
10071
Chris Lattneraab6ec42009-05-13 17:39:14 +000010072 // If the caller function is nounwind, mark the call as nounwind, even if the
10073 // callee isn't.
10074 if (CI.getParent()->getParent()->doesNotThrow() &&
10075 !CI.doesNotThrow()) {
10076 CI.setDoesNotThrow();
10077 return &CI;
10078 }
10079
Chris Lattner8b0ea312006-01-13 20:11:04 +000010080 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10081 if (!II) return visitCallSite(&CI);
10082
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010083 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10084 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010085 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010086 bool Changed = false;
10087
10088 // memmove/cpy/set of zero bytes is a noop.
10089 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10090 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10091
Chris Lattner35b9e482004-10-12 04:52:52 +000010092 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010093 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010094 // Replace the instruction with just byte operations. We would
10095 // transform other cases to loads/stores, but we don't know if
10096 // alignment is sufficient.
10097 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010098 }
10099
Chris Lattner35b9e482004-10-12 04:52:52 +000010100 // If we have a memmove and the source operation is a constant global,
10101 // then the source and dest pointers can't alias, so we can change this
10102 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010103 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010104 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10105 if (GVSrc->isConstant()) {
10106 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010107 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10108 const Type *Tys[1];
10109 Tys[0] = CI.getOperand(3)->getType();
10110 CI.setOperand(0,
10111 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010112 Changed = true;
10113 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010114 }
Chris Lattnera935db82008-05-28 05:30:41 +000010115
Eli Friedman0c826d92009-12-17 21:07:31 +000010116 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010117 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010118 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010119 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010120 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010121
Chris Lattner95a959d2006-03-06 20:18:44 +000010122 // If we can determine a pointer alignment that is bigger than currently
10123 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010124 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010125 if (Instruction *I = SimplifyMemTransfer(MI))
10126 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010127 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10128 if (Instruction *I = SimplifyMemSet(MSI))
10129 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010130 }
10131
Chris Lattner8b0ea312006-01-13 20:11:04 +000010132 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010133 }
10134
10135 switch (II->getIntrinsicID()) {
10136 default: break;
10137 case Intrinsic::bswap:
10138 // bswap(bswap(x)) -> x
10139 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10140 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10141 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
10142 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010143 case Intrinsic::powi:
10144 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10145 // powi(x, 0) -> 1.0
10146 if (Power->isZero())
10147 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10148 // powi(x, 1) -> x
10149 if (Power->isOne())
10150 return ReplaceInstUsesWith(CI, II->getOperand(1));
10151 // powi(x, -1) -> 1/x
10152 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10153 II->getOperand(1));
10154 }
10155 break;
10156
Chris Lattner2bbac752009-11-26 21:42:47 +000010157 case Intrinsic::uadd_with_overflow: {
10158 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10159 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10160 uint32_t BitWidth = IT->getBitWidth();
10161 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010162 APInt LHSKnownZero(BitWidth, 0);
10163 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010164 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10165 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10166 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10167
10168 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010169 APInt RHSKnownZero(BitWidth, 0);
10170 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010171 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10172 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10173 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10174 if (LHSKnownNegative && RHSKnownNegative) {
10175 // The sign bit is set in both cases: this MUST overflow.
10176 // Create a simple add instruction, and insert it into the struct.
10177 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10178 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010179 Constant *V[] = {
10180 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10181 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010182 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10183 return InsertValueInst::Create(Struct, Add, 0);
10184 }
10185
10186 if (LHSKnownPositive && RHSKnownPositive) {
10187 // The sign bit is clear in both cases: this CANNOT overflow.
10188 // Create a simple add instruction, and insert it into the struct.
10189 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10190 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010191 Constant *V[] = {
10192 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10193 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010194 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10195 return InsertValueInst::Create(Struct, Add, 0);
10196 }
10197 }
10198 }
10199 // FALL THROUGH uadd into sadd
10200 case Intrinsic::sadd_with_overflow:
10201 // Canonicalize constants into the RHS.
10202 if (isa<Constant>(II->getOperand(1)) &&
10203 !isa<Constant>(II->getOperand(2))) {
10204 Value *LHS = II->getOperand(1);
10205 II->setOperand(1, II->getOperand(2));
10206 II->setOperand(2, LHS);
10207 return II;
10208 }
10209
10210 // X + undef -> undef
10211 if (isa<UndefValue>(II->getOperand(2)))
10212 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10213
10214 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10215 // X + 0 -> {X, false}
10216 if (RHS->isZero()) {
10217 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010218 UndefValue::get(II->getOperand(0)->getType()),
10219 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010220 };
10221 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10222 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10223 }
10224 }
10225 break;
10226 case Intrinsic::usub_with_overflow:
10227 case Intrinsic::ssub_with_overflow:
10228 // undef - X -> undef
10229 // X - undef -> undef
10230 if (isa<UndefValue>(II->getOperand(1)) ||
10231 isa<UndefValue>(II->getOperand(2)))
10232 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10233
10234 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10235 // X - 0 -> {X, false}
10236 if (RHS->isZero()) {
10237 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010238 UndefValue::get(II->getOperand(1)->getType()),
10239 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010240 };
10241 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10242 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10243 }
10244 }
10245 break;
10246 case Intrinsic::umul_with_overflow:
10247 case Intrinsic::smul_with_overflow:
10248 // Canonicalize constants into the RHS.
10249 if (isa<Constant>(II->getOperand(1)) &&
10250 !isa<Constant>(II->getOperand(2))) {
10251 Value *LHS = II->getOperand(1);
10252 II->setOperand(1, II->getOperand(2));
10253 II->setOperand(2, LHS);
10254 return II;
10255 }
10256
10257 // X * undef -> undef
10258 if (isa<UndefValue>(II->getOperand(2)))
10259 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10260
10261 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10262 // X*0 -> {0, false}
10263 if (RHSI->isZero())
10264 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10265
10266 // X * 1 -> {X, false}
10267 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010268 Constant *V[] = {
10269 UndefValue::get(II->getOperand(1)->getType()),
10270 ConstantInt::getFalse(*Context)
10271 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010272 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010273 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010274 }
10275 }
10276 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010277 case Intrinsic::ppc_altivec_lvx:
10278 case Intrinsic::ppc_altivec_lvxl:
10279 case Intrinsic::x86_sse_loadu_ps:
10280 case Intrinsic::x86_sse2_loadu_pd:
10281 case Intrinsic::x86_sse2_loadu_dq:
10282 // Turn PPC lvx -> load if the pointer is known aligned.
10283 // Turn X86 loadups -> load if the pointer is known aligned.
10284 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010285 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10286 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010287 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010288 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010289 break;
10290 case Intrinsic::ppc_altivec_stvx:
10291 case Intrinsic::ppc_altivec_stvxl:
10292 // Turn stvx -> store if the pointer is known aligned.
10293 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10294 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010295 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010296 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010297 return new StoreInst(II->getOperand(1), Ptr);
10298 }
10299 break;
10300 case Intrinsic::x86_sse_storeu_ps:
10301 case Intrinsic::x86_sse2_storeu_pd:
10302 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010303 // Turn X86 storeu -> store if the pointer is known aligned.
10304 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10305 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010306 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010307 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010308 return new StoreInst(II->getOperand(2), Ptr);
10309 }
10310 break;
10311
10312 case Intrinsic::x86_sse_cvttss2si: {
10313 // These intrinsics only demands the 0th element of its input vector. If
10314 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010315 unsigned VWidth =
10316 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10317 APInt DemandedElts(VWidth, 1);
10318 APInt UndefElts(VWidth, 0);
10319 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010320 UndefElts)) {
10321 II->setOperand(1, V);
10322 return II;
10323 }
10324 break;
10325 }
10326
10327 case Intrinsic::ppc_altivec_vperm:
10328 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10329 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10330 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010331
Chris Lattner0521e3c2008-06-18 04:33:20 +000010332 // Check that all of the elements are integer constants or undefs.
10333 bool AllEltsOk = true;
10334 for (unsigned i = 0; i != 16; ++i) {
10335 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10336 !isa<UndefValue>(Mask->getOperand(i))) {
10337 AllEltsOk = false;
10338 break;
10339 }
10340 }
10341
10342 if (AllEltsOk) {
10343 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010344 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10345 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010346 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010347
Chris Lattner0521e3c2008-06-18 04:33:20 +000010348 // Only extract each element once.
10349 Value *ExtractedElts[32];
10350 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10351
Chris Lattnere2ed0572006-04-06 19:19:17 +000010352 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010353 if (isa<UndefValue>(Mask->getOperand(i)))
10354 continue;
10355 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10356 Idx &= 31; // Match the hardware behavior.
10357
10358 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010359 ExtractedElts[Idx] =
10360 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10361 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10362 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010363 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010364
Chris Lattner0521e3c2008-06-18 04:33:20 +000010365 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010366 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10367 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10368 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010369 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010370 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010371 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010372 }
10373 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010374
Chris Lattner0521e3c2008-06-18 04:33:20 +000010375 case Intrinsic::stackrestore: {
10376 // If the save is right next to the restore, remove the restore. This can
10377 // happen when variable allocas are DCE'd.
10378 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10379 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10380 BasicBlock::iterator BI = SS;
10381 if (&*++BI == II)
10382 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010383 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010384 }
10385
10386 // Scan down this block to see if there is another stack restore in the
10387 // same block without an intervening call/alloca.
10388 BasicBlock::iterator BI = II;
10389 TerminatorInst *TI = II->getParent()->getTerminator();
10390 bool CannotRemove = false;
10391 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010392 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010393 CannotRemove = true;
10394 break;
10395 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010396 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10397 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10398 // If there is a stackrestore below this one, remove this one.
10399 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10400 return EraseInstFromFunction(CI);
10401 // Otherwise, ignore the intrinsic.
10402 } else {
10403 // If we found a non-intrinsic call, we can't remove the stack
10404 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010405 CannotRemove = true;
10406 break;
10407 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010408 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010409 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010410
10411 // If the stack restore is in a return/unwind block and if there are no
10412 // allocas or calls between the restore and the return, nuke the restore.
10413 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10414 return EraseInstFromFunction(CI);
10415 break;
10416 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010417 }
10418
Chris Lattner8b0ea312006-01-13 20:11:04 +000010419 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010420}
10421
10422// InvokeInst simplification
10423//
10424Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010425 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010426}
10427
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010428/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10429/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010430static bool isSafeToEliminateVarargsCast(const CallSite CS,
10431 const CastInst * const CI,
10432 const TargetData * const TD,
10433 const int ix) {
10434 if (!CI->isLosslessCast())
10435 return false;
10436
10437 // The size of ByVal arguments is derived from the type, so we
10438 // can't change to a type with a different size. If the size were
10439 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010440 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010441 return true;
10442
10443 const Type* SrcTy =
10444 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10445 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10446 if (!SrcTy->isSized() || !DstTy->isSized())
10447 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010448 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010449 return false;
10450 return true;
10451}
10452
Chris Lattnera44d8a22003-10-07 22:32:43 +000010453// visitCallSite - Improvements for call and invoke instructions.
10454//
10455Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010456 bool Changed = false;
10457
10458 // If the callee is a constexpr cast of a function, attempt to move the cast
10459 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010460 if (transformConstExprCastCall(CS)) return 0;
10461
Chris Lattner6c266db2003-10-07 22:54:13 +000010462 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010463
Chris Lattner08b22ec2005-05-13 07:09:09 +000010464 if (Function *CalleeF = dyn_cast<Function>(Callee))
10465 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10466 Instruction *OldCall = CS.getInstruction();
10467 // If the call and callee calling conventions don't match, this call must
10468 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010469 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010470 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010471 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010472 // If OldCall dues not return void then replaceAllUsesWith undef.
10473 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010474 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010475 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010476 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10477 return EraseInstFromFunction(*OldCall);
10478 return 0;
10479 }
10480
Chris Lattner17be6352004-10-18 02:59:09 +000010481 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10482 // This instruction is not reachable, just remove it. We insert a store to
10483 // undef so that we know that this code is not reachable, despite the fact
10484 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010485 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010486 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010487 CS.getInstruction());
10488
Devang Patel228ebd02009-10-13 22:56:32 +000010489 // If CS dues not return void then replaceAllUsesWith undef.
10490 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010491 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010492 CS.getInstruction()->
10493 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010494
10495 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10496 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010497 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010498 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010499 }
Chris Lattner17be6352004-10-18 02:59:09 +000010500 return EraseInstFromFunction(*CS.getInstruction());
10501 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010502
Duncan Sandscdb6d922007-09-17 10:26:40 +000010503 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10504 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10505 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10506 return transformCallThroughTrampoline(CS);
10507
Chris Lattner6c266db2003-10-07 22:54:13 +000010508 const PointerType *PTy = cast<PointerType>(Callee->getType());
10509 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10510 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010511 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010512 // See if we can optimize any arguments passed through the varargs area of
10513 // the call.
10514 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010515 E = CS.arg_end(); I != E; ++I, ++ix) {
10516 CastInst *CI = dyn_cast<CastInst>(*I);
10517 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10518 *I = CI->getOperand(0);
10519 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010520 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010521 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010522 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010523
Duncan Sandsf0c33542007-12-19 21:13:37 +000010524 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010525 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010526 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010527 Changed = true;
10528 }
10529
Chris Lattner6c266db2003-10-07 22:54:13 +000010530 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010531}
10532
Chris Lattner9fe38862003-06-19 17:00:31 +000010533// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10534// attempt to move the cast to the arguments of the call/invoke.
10535//
10536bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10537 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10538 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010539 if (CE->getOpcode() != Instruction::BitCast ||
10540 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010541 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010542 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010543 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010544 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010545
10546 // Okay, this is a cast from a function to a different type. Unless doing so
10547 // would cause a type conversion of one of our arguments, change this call to
10548 // be a direct call with arguments casted to the appropriate types.
10549 //
10550 const FunctionType *FT = Callee->getFunctionType();
10551 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010552 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010553
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010554 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010555 return false; // TODO: Handle multiple return values.
10556
Chris Lattnerf78616b2004-01-14 06:06:08 +000010557 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010558 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010559 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010560 // Conversion is ok if changing from one pointer type to another or from
10561 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010562 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010563 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010564 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010565 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010566 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010567
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010568 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010569 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010570 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010571 return false; // Cannot transform this return value.
10572
Chris Lattner58d74912008-03-12 17:45:29 +000010573 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010574 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010575 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010576 return false; // Attribute not compatible with transformed value.
10577 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010578
Chris Lattnerf78616b2004-01-14 06:06:08 +000010579 // If the callsite is an invoke instruction, and the return value is used by
10580 // a PHI node in a successor, we cannot change the return type of the call
10581 // because there is no place to put the cast instruction (without breaking
10582 // the critical edge). Bail out in this case.
10583 if (!Caller->use_empty())
10584 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10585 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10586 UI != E; ++UI)
10587 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10588 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010589 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010590 return false;
10591 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010592
10593 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10594 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010595
Chris Lattner9fe38862003-06-19 17:00:31 +000010596 CallSite::arg_iterator AI = CS.arg_begin();
10597 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10598 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010599 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010600
10601 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010602 return false; // Cannot transform this parameter value.
10603
Devang Patel19c87462008-09-26 22:53:05 +000010604 if (CallerPAL.getParamAttributes(i + 1)
10605 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010606 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010607
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010608 // Converting from one pointer type to another or between a pointer and an
10609 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010610 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010611 (TD && ((isa<PointerType>(ParamTy) ||
10612 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10613 (isa<PointerType>(ActTy) ||
10614 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010615 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010616 }
10617
10618 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010619 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010620 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010621
Chris Lattner58d74912008-03-12 17:45:29 +000010622 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10623 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010624 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010625 // won't be dropping them. Check that these extra arguments have attributes
10626 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010627 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10628 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010629 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010630 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010631 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010632 return false;
10633 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010634
Chris Lattner9fe38862003-06-19 17:00:31 +000010635 // Okay, we decided that this is a safe thing to do: go ahead and start
10636 // inserting cast instructions as necessary...
10637 std::vector<Value*> Args;
10638 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010639 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010640 attrVec.reserve(NumCommonArgs);
10641
10642 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010643 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010644
10645 // If the return value is not being used, the type may not be compatible
10646 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010647 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010648
10649 // Add the new return attributes.
10650 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010651 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010652
10653 AI = CS.arg_begin();
10654 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10655 const Type *ParamTy = FT->getParamType(i);
10656 if ((*AI)->getType() == ParamTy) {
10657 Args.push_back(*AI);
10658 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010659 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010660 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010661 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010662 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010663
10664 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010665 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010666 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010667 }
10668
10669 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010670 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010671 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010672 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010673
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010674 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010675 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010676 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010677 errs() << "WARNING: While resolving call to function '"
10678 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010679 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010680 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010681 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10682 const Type *PTy = getPromotedType((*AI)->getType());
10683 if (PTy != (*AI)->getType()) {
10684 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010685 Instruction::CastOps opcode =
10686 CastInst::getCastOpcode(*AI, false, PTy, false);
10687 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010688 } else {
10689 Args.push_back(*AI);
10690 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010691
Duncan Sandse1e520f2008-01-13 08:02:44 +000010692 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010693 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010694 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010695 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010696 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010697 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010698
Devang Patel19c87462008-09-26 22:53:05 +000010699 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10700 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10701
Devang Patel9674d152009-10-14 17:29:00 +000010702 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010703 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010704
Eric Christophera66297a2009-07-25 02:45:27 +000010705 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10706 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010707
Chris Lattner9fe38862003-06-19 17:00:31 +000010708 Instruction *NC;
10709 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010710 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010711 Args.begin(), Args.end(),
10712 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010713 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010714 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010715 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010716 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10717 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010718 CallInst *CI = cast<CallInst>(Caller);
10719 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010720 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010721 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010722 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010723 }
10724
Chris Lattner6934a042007-02-11 01:23:03 +000010725 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010726 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010727 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010728 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010729 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010730 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010731 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010732
10733 // If this is an invoke instruction, we should insert it after the first
10734 // non-phi, instruction in the normal successor block.
10735 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010736 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010737 InsertNewInstBefore(NC, *I);
10738 } else {
10739 // Otherwise, it's a call, just insert cast right after the call instr
10740 InsertNewInstBefore(NC, *Caller);
10741 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010742 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010743 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010744 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010745 }
10746 }
10747
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010748
Chris Lattner931f8f32009-08-31 05:17:58 +000010749 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010750 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010751
10752 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010753 return true;
10754}
10755
Duncan Sandscdb6d922007-09-17 10:26:40 +000010756// transformCallThroughTrampoline - Turn a call to a function created by the
10757// init_trampoline intrinsic into a direct call to the underlying function.
10758//
10759Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10760 Value *Callee = CS.getCalledValue();
10761 const PointerType *PTy = cast<PointerType>(Callee->getType());
10762 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010763 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010764
10765 // If the call already has the 'nest' attribute somewhere then give up -
10766 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010767 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010768 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010769
10770 IntrinsicInst *Tramp =
10771 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10772
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010773 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010774 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10775 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10776
Devang Patel05988662008-09-25 21:00:45 +000010777 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010778 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010779 unsigned NestIdx = 1;
10780 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010781 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010782
10783 // Look for a parameter marked with the 'nest' attribute.
10784 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10785 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010786 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010787 // Record the parameter type and any other attributes.
10788 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010789 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010790 break;
10791 }
10792
10793 if (NestTy) {
10794 Instruction *Caller = CS.getInstruction();
10795 std::vector<Value*> NewArgs;
10796 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10797
Devang Patel05988662008-09-25 21:00:45 +000010798 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010799 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010800
Duncan Sandscdb6d922007-09-17 10:26:40 +000010801 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010802 // mean appending it. Likewise for attributes.
10803
Devang Patel19c87462008-09-26 22:53:05 +000010804 // Add any result attributes.
10805 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010806 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010807
Duncan Sandscdb6d922007-09-17 10:26:40 +000010808 {
10809 unsigned Idx = 1;
10810 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10811 do {
10812 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010813 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010814 Value *NestVal = Tramp->getOperand(3);
10815 if (NestVal->getType() != NestTy)
10816 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10817 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010818 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010819 }
10820
10821 if (I == E)
10822 break;
10823
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010824 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010825 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010826 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010827 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010828 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010829
10830 ++Idx, ++I;
10831 } while (1);
10832 }
10833
Devang Patel19c87462008-09-26 22:53:05 +000010834 // Add any function attributes.
10835 if (Attributes Attr = Attrs.getFnAttributes())
10836 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10837
Duncan Sandscdb6d922007-09-17 10:26:40 +000010838 // The trampoline may have been bitcast to a bogus type (FTy).
10839 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010840 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010841
Duncan Sandscdb6d922007-09-17 10:26:40 +000010842 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010843 NewTypes.reserve(FTy->getNumParams()+1);
10844
Duncan Sandscdb6d922007-09-17 10:26:40 +000010845 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010846 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010847 {
10848 unsigned Idx = 1;
10849 FunctionType::param_iterator I = FTy->param_begin(),
10850 E = FTy->param_end();
10851
10852 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010853 if (Idx == NestIdx)
10854 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010855 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010856
10857 if (I == E)
10858 break;
10859
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010860 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010861 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010862
10863 ++Idx, ++I;
10864 } while (1);
10865 }
10866
10867 // Replace the trampoline call with a direct call. Let the generic
10868 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010869 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010870 FTy->isVarArg());
10871 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010872 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010873 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010874 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010875 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10876 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010877
10878 Instruction *NewCaller;
10879 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010880 NewCaller = InvokeInst::Create(NewCallee,
10881 II->getNormalDest(), II->getUnwindDest(),
10882 NewArgs.begin(), NewArgs.end(),
10883 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010884 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010885 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010886 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010887 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10888 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010889 if (cast<CallInst>(Caller)->isTailCall())
10890 cast<CallInst>(NewCaller)->setTailCall();
10891 cast<CallInst>(NewCaller)->
10892 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010893 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010894 }
Devang Patel9674d152009-10-14 17:29:00 +000010895 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010896 Caller->replaceAllUsesWith(NewCaller);
10897 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010898 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010899 return 0;
10900 }
10901 }
10902
10903 // Replace the trampoline call with a direct call. Since there is no 'nest'
10904 // parameter, there is no need to adjust the argument list. Let the generic
10905 // code sort out any function type mismatches.
10906 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010907 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010908 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010909 CS.setCalledFunction(NewCallee);
10910 return CS.getInstruction();
10911}
10912
Dan Gohman9ad29202009-09-16 16:50:24 +000010913/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10914/// 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 +000010915/// and a single binop.
10916Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10917 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010918 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010919 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010920 Value *LHSVal = FirstInst->getOperand(0);
10921 Value *RHSVal = FirstInst->getOperand(1);
10922
10923 const Type *LHSType = LHSVal->getType();
10924 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010925
Dan Gohman9ad29202009-09-16 16:50:24 +000010926 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010927 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010928 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010929 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010930 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010931 // types or GEP's with different index types.
10932 I->getOperand(0)->getType() != LHSType ||
10933 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010934 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010935
10936 // If they are CmpInst instructions, check their predicates
10937 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10938 if (cast<CmpInst>(I)->getPredicate() !=
10939 cast<CmpInst>(FirstInst)->getPredicate())
10940 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010941
10942 // Keep track of which operand needs a phi node.
10943 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10944 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010945 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010946
10947 // If both LHS and RHS would need a PHI, don't do this transformation,
10948 // because it would increase the number of PHIs entering the block,
10949 // which leads to higher register pressure. This is especially
10950 // bad when the PHIs are in the header of a loop.
10951 if (!LHSVal && !RHSVal)
10952 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010953
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010954 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010955
Chris Lattner7da52b22006-11-01 04:51:18 +000010956 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010957 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010958 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010959 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010960 NewLHS = PHINode::Create(LHSType,
10961 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010962 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10963 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010964 InsertNewInstBefore(NewLHS, PN);
10965 LHSVal = NewLHS;
10966 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010967
10968 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010969 NewRHS = PHINode::Create(RHSType,
10970 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010971 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10972 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010973 InsertNewInstBefore(NewRHS, PN);
10974 RHSVal = NewRHS;
10975 }
10976
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010977 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010978 if (NewLHS || NewRHS) {
10979 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10980 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10981 if (NewLHS) {
10982 Value *NewInLHS = InInst->getOperand(0);
10983 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10984 }
10985 if (NewRHS) {
10986 Value *NewInRHS = InInst->getOperand(1);
10987 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10988 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010989 }
10990 }
10991
Chris Lattner7da52b22006-11-01 04:51:18 +000010992 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010993 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010994 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010995 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010996 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010997}
10998
Chris Lattner05f18922008-12-01 02:34:36 +000010999Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11000 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11001
11002 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11003 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000011004 // This is true if all GEP bases are allocas and if all indices into them are
11005 // constants.
11006 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011007
11008 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000011009 // more than one phi, which leads to higher register pressure. This is
11010 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011011 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000011012
Dan Gohman9ad29202009-09-16 16:50:24 +000011013 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011014 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11015 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11016 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11017 GEP->getNumOperands() != FirstInst->getNumOperands())
11018 return 0;
11019
Chris Lattner36d3e322009-02-21 00:46:50 +000011020 // Keep track of whether or not all GEPs are of alloca pointers.
11021 if (AllBasePointersAreAllocas &&
11022 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11023 !GEP->hasAllConstantIndices()))
11024 AllBasePointersAreAllocas = false;
11025
Chris Lattner05f18922008-12-01 02:34:36 +000011026 // Compare the operand lists.
11027 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11028 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11029 continue;
11030
11031 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11032 // if one of the PHIs has a constant for the index. The index may be
11033 // substantially cheaper to compute for the constants, so making it a
11034 // variable index could pessimize the path. This also handles the case
11035 // for struct indices, which must always be constant.
11036 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11037 isa<ConstantInt>(GEP->getOperand(op)))
11038 return 0;
11039
11040 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11041 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011042
11043 // If we already needed a PHI for an earlier operand, and another operand
11044 // also requires a PHI, we'd be introducing more PHIs than we're
11045 // eliminating, which increases register pressure on entry to the PHI's
11046 // block.
11047 if (NeededPhi)
11048 return 0;
11049
Chris Lattner05f18922008-12-01 02:34:36 +000011050 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011051 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011052 }
11053 }
11054
Chris Lattner36d3e322009-02-21 00:46:50 +000011055 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011056 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011057 // offset calculation, but all the predecessors will have to materialize the
11058 // stack address into a register anyway. We'd actually rather *clone* the
11059 // load up into the predecessors so that we have a load of a gep of an alloca,
11060 // which can usually all be folded into the load.
11061 if (AllBasePointersAreAllocas)
11062 return 0;
11063
Chris Lattner05f18922008-12-01 02:34:36 +000011064 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11065 // that is variable.
11066 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11067
11068 bool HasAnyPHIs = false;
11069 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11070 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11071 Value *FirstOp = FirstInst->getOperand(i);
11072 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11073 FirstOp->getName()+".pn");
11074 InsertNewInstBefore(NewPN, PN);
11075
11076 NewPN->reserveOperandSpace(e);
11077 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11078 OperandPhis[i] = NewPN;
11079 FixedOperands[i] = NewPN;
11080 HasAnyPHIs = true;
11081 }
11082
11083
11084 // Add all operands to the new PHIs.
11085 if (HasAnyPHIs) {
11086 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11087 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11088 BasicBlock *InBB = PN.getIncomingBlock(i);
11089
11090 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11091 if (PHINode *OpPhi = OperandPhis[op])
11092 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11093 }
11094 }
11095
11096 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011097 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11098 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11099 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011100 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11101 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011102}
11103
11104
Chris Lattner21550882009-02-23 05:56:17 +000011105/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11106/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011107/// obvious the value of the load is not changed from the point of the load to
11108/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011109///
11110/// Finally, it is safe, but not profitable, to sink a load targetting a
11111/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11112/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011113static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011114 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11115
11116 for (++BBI; BBI != E; ++BBI)
11117 if (BBI->mayWriteToMemory())
11118 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011119
11120 // Check for non-address taken alloca. If not address-taken already, it isn't
11121 // profitable to do this xform.
11122 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11123 bool isAddressTaken = false;
11124 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11125 UI != E; ++UI) {
11126 if (isa<LoadInst>(UI)) continue;
11127 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11128 // If storing TO the alloca, then the address isn't taken.
11129 if (SI->getOperand(1) == AI) continue;
11130 }
11131 isAddressTaken = true;
11132 break;
11133 }
11134
Chris Lattner36d3e322009-02-21 00:46:50 +000011135 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011136 return false;
11137 }
11138
Chris Lattner36d3e322009-02-21 00:46:50 +000011139 // If this load is a load from a GEP with a constant offset from an alloca,
11140 // then we don't want to sink it. In its present form, it will be
11141 // load [constant stack offset]. Sinking it will cause us to have to
11142 // materialize the stack addresses in each predecessor in a register only to
11143 // do a shared load from register in the successor.
11144 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11145 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11146 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11147 return false;
11148
Chris Lattner76c73142006-11-01 07:13:54 +000011149 return true;
11150}
11151
Chris Lattner751a3622009-11-01 20:04:24 +000011152Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11153 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11154
11155 // When processing loads, we need to propagate two bits of information to the
11156 // sunk load: whether it is volatile, and what its alignment is. We currently
11157 // don't sink loads when some have their alignment specified and some don't.
11158 // visitLoadInst will propagate an alignment onto the load when TD is around,
11159 // and if TD isn't around, we can't handle the mixed case.
11160 bool isVolatile = FirstLI->isVolatile();
11161 unsigned LoadAlignment = FirstLI->getAlignment();
11162
11163 // We can't sink the load if the loaded value could be modified between the
11164 // load and the PHI.
11165 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11166 !isSafeAndProfitableToSinkLoad(FirstLI))
11167 return 0;
11168
11169 // If the PHI is of volatile loads and the load block has multiple
11170 // successors, sinking it would remove a load of the volatile value from
11171 // the path through the other successor.
11172 if (isVolatile &&
11173 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11174 return 0;
11175
11176 // Check to see if all arguments are the same operation.
11177 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11178 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11179 if (!LI || !LI->hasOneUse())
11180 return 0;
11181
11182 // We can't sink the load if the loaded value could be modified between
11183 // the load and the PHI.
11184 if (LI->isVolatile() != isVolatile ||
11185 LI->getParent() != PN.getIncomingBlock(i) ||
11186 !isSafeAndProfitableToSinkLoad(LI))
11187 return 0;
11188
11189 // If some of the loads have an alignment specified but not all of them,
11190 // we can't do the transformation.
11191 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11192 return 0;
11193
Chris Lattnera664bb72009-11-01 20:07:07 +000011194 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011195
11196 // If the PHI is of volatile loads and the load block has multiple
11197 // successors, sinking it would remove a load of the volatile value from
11198 // the path through the other successor.
11199 if (isVolatile &&
11200 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11201 return 0;
11202 }
11203
11204 // Okay, they are all the same operation. Create a new PHI node of the
11205 // correct type, and PHI together all of the LHS's of the instructions.
11206 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11207 PN.getName()+".in");
11208 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11209
11210 Value *InVal = FirstLI->getOperand(0);
11211 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11212
11213 // Add all operands to the new PHI.
11214 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11215 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11216 if (NewInVal != InVal)
11217 InVal = 0;
11218 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11219 }
11220
11221 Value *PhiVal;
11222 if (InVal) {
11223 // The new PHI unions all of the same values together. This is really
11224 // common, so we handle it intelligently here for compile-time speed.
11225 PhiVal = InVal;
11226 delete NewPN;
11227 } else {
11228 InsertNewInstBefore(NewPN, PN);
11229 PhiVal = NewPN;
11230 }
11231
11232 // If this was a volatile load that we are merging, make sure to loop through
11233 // and mark all the input loads as non-volatile. If we don't do this, we will
11234 // insert a new volatile load and the old ones will not be deletable.
11235 if (isVolatile)
11236 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11237 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11238
11239 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11240}
11241
Chris Lattner9fe38862003-06-19 17:00:31 +000011242
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011243
11244/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11245/// operator and they all are only used by the PHI, PHI together their
11246/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011247Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11248 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11249
Chris Lattner751a3622009-11-01 20:04:24 +000011250 if (isa<GetElementPtrInst>(FirstInst))
11251 return FoldPHIArgGEPIntoPHI(PN);
11252 if (isa<LoadInst>(FirstInst))
11253 return FoldPHIArgLoadIntoPHI(PN);
11254
Chris Lattnerbac32862004-11-14 19:13:23 +000011255 // Scan the instruction, looking for input operations that can be folded away.
11256 // If all input operands to the phi are the same instruction (e.g. a cast from
11257 // the same type or "+42") we can pull the operation through the PHI, reducing
11258 // code size and simplifying code.
11259 Constant *ConstantOp = 0;
11260 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011261
Chris Lattnerbac32862004-11-14 19:13:23 +000011262 if (isa<CastInst>(FirstInst)) {
11263 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011264
11265 // Be careful about transforming integer PHIs. We don't want to pessimize
11266 // the code by turning an i32 into an i1293.
11267 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011268 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011269 return 0;
11270 }
Reid Spencer832254e2007-02-02 02:16:23 +000011271 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011272 // Can fold binop, compare or shift here if the RHS is a constant,
11273 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011274 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011275 if (ConstantOp == 0)
11276 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011277 } else {
11278 return 0; // Cannot fold this operation.
11279 }
11280
11281 // Check to see if all arguments are the same operation.
11282 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011283 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11284 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011285 return 0;
11286 if (CastSrcTy) {
11287 if (I->getOperand(0)->getType() != CastSrcTy)
11288 return 0; // Cast operation must match.
11289 } else if (I->getOperand(1) != ConstantOp) {
11290 return 0;
11291 }
11292 }
11293
11294 // Okay, they are all the same operation. Create a new PHI node of the
11295 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011296 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11297 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011298 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011299
11300 Value *InVal = FirstInst->getOperand(0);
11301 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011302
11303 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011304 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11305 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11306 if (NewInVal != InVal)
11307 InVal = 0;
11308 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11309 }
11310
11311 Value *PhiVal;
11312 if (InVal) {
11313 // The new PHI unions all of the same values together. This is really
11314 // common, so we handle it intelligently here for compile-time speed.
11315 PhiVal = InVal;
11316 delete NewPN;
11317 } else {
11318 InsertNewInstBefore(NewPN, PN);
11319 PhiVal = NewPN;
11320 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011321
Chris Lattnerbac32862004-11-14 19:13:23 +000011322 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011323 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011324 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011325
Chris Lattner54545ac2008-04-29 17:13:43 +000011326 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011327 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011328
Chris Lattner751a3622009-11-01 20:04:24 +000011329 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11330 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11331 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011332}
Chris Lattnera1be5662002-05-02 17:06:02 +000011333
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011334/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11335/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011336static bool DeadPHICycle(PHINode *PN,
11337 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011338 if (PN->use_empty()) return true;
11339 if (!PN->hasOneUse()) return false;
11340
11341 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011342 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011343 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011344
11345 // Don't scan crazily complex things.
11346 if (PotentiallyDeadPHIs.size() == 16)
11347 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011348
11349 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11350 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011351
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011352 return false;
11353}
11354
Chris Lattnercf5008a2007-11-06 21:52:06 +000011355/// PHIsEqualValue - Return true if this phi node is always equal to
11356/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11357/// z = some value; x = phi (y, z); y = phi (x, z)
11358static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11359 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11360 // See if we already saw this PHI node.
11361 if (!ValueEqualPHIs.insert(PN))
11362 return true;
11363
11364 // Don't scan crazily complex things.
11365 if (ValueEqualPHIs.size() == 16)
11366 return false;
11367
11368 // Scan the operands to see if they are either phi nodes or are equal to
11369 // the value.
11370 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11371 Value *Op = PN->getIncomingValue(i);
11372 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11373 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11374 return false;
11375 } else if (Op != NonPhiInVal)
11376 return false;
11377 }
11378
11379 return true;
11380}
11381
11382
Chris Lattner9956c052009-11-08 19:23:30 +000011383namespace {
11384struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011385 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011386 unsigned Shift; // The amount shifted.
11387 Instruction *Inst; // The trunc instruction.
11388
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011389 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11390 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011391
11392 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011393 if (PHIId < RHS.PHIId) return true;
11394 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011395 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011396 if (Shift > RHS.Shift) return false;
11397 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011398 RHS.Inst->getType()->getPrimitiveSizeInBits();
11399 }
11400};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011401
11402struct LoweredPHIRecord {
11403 PHINode *PN; // The PHI that was lowered.
11404 unsigned Shift; // The amount shifted.
11405 unsigned Width; // The width extracted.
11406
11407 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11408 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11409
11410 // Ctor form used by DenseMap.
11411 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11412 : PN(pn), Shift(Sh), Width(0) {}
11413};
11414}
11415
11416namespace llvm {
11417 template<>
11418 struct DenseMapInfo<LoweredPHIRecord> {
11419 static inline LoweredPHIRecord getEmptyKey() {
11420 return LoweredPHIRecord(0, 0);
11421 }
11422 static inline LoweredPHIRecord getTombstoneKey() {
11423 return LoweredPHIRecord(0, 1);
11424 }
11425 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11426 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11427 (Val.Width>>3);
11428 }
11429 static bool isEqual(const LoweredPHIRecord &LHS,
11430 const LoweredPHIRecord &RHS) {
11431 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11432 LHS.Width == RHS.Width;
11433 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011434 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011435 template <>
11436 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011437}
11438
11439
11440/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11441/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11442/// so, we split the PHI into the various pieces being extracted. This sort of
11443/// thing is introduced when SROA promotes an aggregate to large integer values.
11444///
11445/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11446/// inttoptr. We should produce new PHIs in the right type.
11447///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011448Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11449 // PHIUsers - Keep track of all of the truncated values extracted from a set
11450 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011451 SmallVector<PHIUsageRecord, 16> PHIUsers;
11452
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011453 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11454 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11455 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11456 // check the uses of (to ensure they are all extracts).
11457 SmallVector<PHINode*, 8> PHIsToSlice;
11458 SmallPtrSet<PHINode*, 8> PHIsInspected;
11459
11460 PHIsToSlice.push_back(&FirstPhi);
11461 PHIsInspected.insert(&FirstPhi);
11462
11463 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11464 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011465
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011466 // Scan the input list of the PHI. If any input is an invoke, and if the
11467 // input is defined in the predecessor, then we won't be split the critical
11468 // edge which is required to insert a truncate. Because of this, we have to
11469 // bail out.
11470 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11471 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11472 if (II == 0) continue;
11473 if (II->getParent() != PN->getIncomingBlock(i))
11474 continue;
11475
11476 // If we have a phi, and if it's directly in the predecessor, then we have
11477 // a critical edge where we need to put the truncate. Since we can't
11478 // split the edge in instcombine, we have to bail out.
11479 return 0;
11480 }
11481
11482
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011483 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11484 UI != E; ++UI) {
11485 Instruction *User = cast<Instruction>(*UI);
11486
11487 // If the user is a PHI, inspect its uses recursively.
11488 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11489 if (PHIsInspected.insert(UserPN))
11490 PHIsToSlice.push_back(UserPN);
11491 continue;
11492 }
11493
11494 // Truncates are always ok.
11495 if (isa<TruncInst>(User)) {
11496 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11497 continue;
11498 }
11499
11500 // Otherwise it must be a lshr which can only be used by one trunc.
11501 if (User->getOpcode() != Instruction::LShr ||
11502 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11503 !isa<ConstantInt>(User->getOperand(1)))
11504 return 0;
11505
11506 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11507 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011508 }
Chris Lattner9956c052009-11-08 19:23:30 +000011509 }
11510
11511 // If we have no users, they must be all self uses, just nuke the PHI.
11512 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011513 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011514
11515 // If this phi node is transformable, create new PHIs for all the pieces
11516 // extracted out of it. First, sort the users by their offset and size.
11517 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11518
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011519 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11520 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11521 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11522 );
Chris Lattner9956c052009-11-08 19:23:30 +000011523
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011524 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11525 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011526 DenseMap<BasicBlock*, Value*> PredValues;
11527
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011528 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11529 // introduce redundant PHIs.
11530 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11531
11532 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11533 unsigned PHIId = PHIUsers[UserI].PHIId;
11534 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011535 unsigned Offset = PHIUsers[UserI].Shift;
11536 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011537
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011538 PHINode *EltPHI;
11539
11540 // If we've already lowered a user like this, reuse the previously lowered
11541 // value.
11542 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011543
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011544 // Otherwise, Create the new PHI node for this user.
11545 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11546 assert(EltPHI->getType() != PN->getType() &&
11547 "Truncate didn't shrink phi?");
11548
11549 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11550 BasicBlock *Pred = PN->getIncomingBlock(i);
11551 Value *&PredVal = PredValues[Pred];
11552
11553 // If we already have a value for this predecessor, reuse it.
11554 if (PredVal) {
11555 EltPHI->addIncoming(PredVal, Pred);
11556 continue;
11557 }
Chris Lattner9956c052009-11-08 19:23:30 +000011558
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011559 // Handle the PHI self-reuse case.
11560 Value *InVal = PN->getIncomingValue(i);
11561 if (InVal == PN) {
11562 PredVal = EltPHI;
11563 EltPHI->addIncoming(PredVal, Pred);
11564 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011565 }
11566
11567 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011568 // If the incoming value was a PHI, and if it was one of the PHIs we
11569 // already rewrote it, just use the lowered value.
11570 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11571 PredVal = Res;
11572 EltPHI->addIncoming(PredVal, Pred);
11573 continue;
11574 }
11575 }
11576
11577 // Otherwise, do an extract in the predecessor.
11578 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11579 Value *Res = InVal;
11580 if (Offset)
11581 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11582 Offset), "extract");
11583 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11584 PredVal = Res;
11585 EltPHI->addIncoming(Res, Pred);
11586
11587 // If the incoming value was a PHI, and if it was one of the PHIs we are
11588 // rewriting, we will ultimately delete the code we inserted. This
11589 // means we need to revisit that PHI to make sure we extract out the
11590 // needed piece.
11591 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11592 if (PHIsInspected.count(OldInVal)) {
11593 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11594 OldInVal)-PHIsToSlice.begin();
11595 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11596 cast<Instruction>(Res)));
11597 ++UserE;
11598 }
Chris Lattner9956c052009-11-08 19:23:30 +000011599 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011600 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011601
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011602 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11603 << *EltPHI << '\n');
11604 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011605 }
Chris Lattner9956c052009-11-08 19:23:30 +000011606
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011607 // Replace the use of this piece with the PHI node.
11608 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011609 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011610
11611 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11612 // with undefs.
11613 Value *Undef = UndefValue::get(FirstPhi.getType());
11614 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11615 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11616 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011617}
11618
Chris Lattner473945d2002-05-06 18:06:38 +000011619// PHINode simplification
11620//
Chris Lattner7e708292002-06-25 16:13:24 +000011621Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011622 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011623 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011624
Owen Anderson7e057142006-07-10 22:03:18 +000011625 if (Value *V = PN.hasConstantValue())
11626 return ReplaceInstUsesWith(PN, V);
11627
Owen Anderson7e057142006-07-10 22:03:18 +000011628 // If all PHI operands are the same operation, pull them through the PHI,
11629 // reducing code size.
11630 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011631 isa<Instruction>(PN.getIncomingValue(1)) &&
11632 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11633 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11634 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11635 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011636 PN.getIncomingValue(0)->hasOneUse())
11637 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11638 return Result;
11639
11640 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11641 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11642 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011643 if (PN.hasOneUse()) {
11644 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11645 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011646 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011647 PotentiallyDeadPHIs.insert(&PN);
11648 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011649 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011650 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011651
11652 // If this phi has a single use, and if that use just computes a value for
11653 // the next iteration of a loop, delete the phi. This occurs with unused
11654 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11655 // common case here is good because the only other things that catch this
11656 // are induction variable analysis (sometimes) and ADCE, which is only run
11657 // late.
11658 if (PHIUser->hasOneUse() &&
11659 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11660 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011661 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011662 }
11663 }
Owen Anderson7e057142006-07-10 22:03:18 +000011664
Chris Lattnercf5008a2007-11-06 21:52:06 +000011665 // We sometimes end up with phi cycles that non-obviously end up being the
11666 // same value, for example:
11667 // z = some value; x = phi (y, z); y = phi (x, z)
11668 // where the phi nodes don't necessarily need to be in the same block. Do a
11669 // quick check to see if the PHI node only contains a single non-phi value, if
11670 // so, scan to see if the phi cycle is actually equal to that value.
11671 {
11672 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11673 // Scan for the first non-phi operand.
11674 while (InValNo != NumOperandVals &&
11675 isa<PHINode>(PN.getIncomingValue(InValNo)))
11676 ++InValNo;
11677
11678 if (InValNo != NumOperandVals) {
11679 Value *NonPhiInVal = PN.getOperand(InValNo);
11680
11681 // Scan the rest of the operands to see if there are any conflicts, if so
11682 // there is no need to recursively scan other phis.
11683 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11684 Value *OpVal = PN.getIncomingValue(InValNo);
11685 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11686 break;
11687 }
11688
11689 // If we scanned over all operands, then we have one unique value plus
11690 // phi values. Scan PHI nodes to see if they all merge in each other or
11691 // the value.
11692 if (InValNo == NumOperandVals) {
11693 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11694 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11695 return ReplaceInstUsesWith(PN, NonPhiInVal);
11696 }
11697 }
11698 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011699
Dan Gohman5b097012009-10-31 14:22:52 +000011700 // If there are multiple PHIs, sort their operands so that they all list
11701 // the blocks in the same order. This will help identical PHIs be eliminated
11702 // by other passes. Other passes shouldn't depend on this for correctness
11703 // however.
11704 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11705 if (&PN != FirstPN)
11706 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011707 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011708 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11709 if (BBA != BBB) {
11710 Value *VA = PN.getIncomingValue(i);
11711 unsigned j = PN.getBasicBlockIndex(BBB);
11712 Value *VB = PN.getIncomingValue(j);
11713 PN.setIncomingBlock(i, BBB);
11714 PN.setIncomingValue(i, VB);
11715 PN.setIncomingBlock(j, BBA);
11716 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011717 // NOTE: Instcombine normally would want us to "return &PN" if we
11718 // modified any of the operands of an instruction. However, since we
11719 // aren't adding or removing uses (just rearranging them) we don't do
11720 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011721 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011722 }
11723
Chris Lattner9956c052009-11-08 19:23:30 +000011724 // If this is an integer PHI and we know that it has an illegal type, see if
11725 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11726 // PHI into the various pieces being extracted. This sort of thing is
11727 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011728 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011729 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11730 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11731 return Res;
11732
Chris Lattner60921c92003-12-19 05:58:40 +000011733 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011734}
11735
Chris Lattner7e708292002-06-25 16:13:24 +000011736Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011737 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11738
11739 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11740 return ReplaceInstUsesWith(GEP, V);
11741
Chris Lattner620ce142004-05-07 22:09:22 +000011742 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011743
Chris Lattnere87597f2004-10-16 18:11:37 +000011744 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011745 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011746
Chris Lattner28977af2004-04-05 01:30:19 +000011747 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011748 if (TD) {
11749 bool MadeChange = false;
11750 unsigned PtrSize = TD->getPointerSizeInBits();
11751
11752 gep_type_iterator GTI = gep_type_begin(GEP);
11753 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11754 I != E; ++I, ++GTI) {
11755 if (!isa<SequentialType>(*GTI)) continue;
11756
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011757 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011758 // to what we need. If narrower, sign-extend it to what we need. This
11759 // explicit cast can make subsequent optimizations more obvious.
11760 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011761 if (OpBits == PtrSize)
11762 continue;
11763
Chris Lattner2345d1d2009-08-30 20:01:10 +000011764 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011765 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011766 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011767 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011768 }
Chris Lattner28977af2004-04-05 01:30:19 +000011769
Chris Lattner90ac28c2002-08-02 19:29:35 +000011770 // Combine Indices - If the source pointer to this getelementptr instruction
11771 // is a getelementptr instruction, combine the indices of the two
11772 // getelementptr instructions into a single instruction.
11773 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011774 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011775 // Note that if our source is a gep chain itself that we wait for that
11776 // chain to be resolved before we perform this transformation. This
11777 // avoids us creating a TON of code in some cases.
11778 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011779 if (GetElementPtrInst *SrcGEP =
11780 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11781 if (SrcGEP->getNumOperands() == 2)
11782 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011783
Chris Lattner72588fc2007-02-15 22:48:32 +000011784 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011785
11786 // Find out whether the last index in the source GEP is a sequential idx.
11787 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011788 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11789 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011790 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011791
Chris Lattner90ac28c2002-08-02 19:29:35 +000011792 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011793 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011794 // Replace: gep (gep %P, long B), long A, ...
11795 // With: T = long A+B; gep %P, T, ...
11796 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011797 Value *Sum;
11798 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11799 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011800 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011801 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011802 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011803 Sum = SO1;
11804 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011805 // If they aren't the same type, then the input hasn't been processed
11806 // by the loop above yet (which canonicalizes sequential index types to
11807 // intptr_t). Just avoid transforming this until the input has been
11808 // normalized.
11809 if (SO1->getType() != GO1->getType())
11810 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011811 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011812 }
Chris Lattner620ce142004-05-07 22:09:22 +000011813
Chris Lattnerab984842009-08-30 05:30:55 +000011814 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011815 if (Src->getNumOperands() == 2) {
11816 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011817 GEP.setOperand(1, Sum);
11818 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011819 }
Chris Lattnerab984842009-08-30 05:30:55 +000011820 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011821 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011822 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011823 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011824 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011825 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011826 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011827 Indices.append(Src->op_begin()+1, Src->op_end());
11828 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011829 }
11830
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011831 if (!Indices.empty())
11832 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11833 Src->isInBounds()) ?
11834 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11835 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011836 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011837 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011838 }
11839
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011840 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11841 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011842 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011843
Chris Lattner2de23192009-08-30 20:38:21 +000011844 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11845 // want to change the gep until the bitcasts are eliminated.
11846 if (getBitCastOperand(X)) {
11847 Worklist.AddValue(PtrOp);
11848 return 0;
11849 }
11850
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011851 bool HasZeroPointerIndex = false;
11852 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11853 HasZeroPointerIndex = C->isZero();
11854
Chris Lattner963f4ba2009-08-30 20:36:46 +000011855 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11856 // into : GEP [10 x i8]* X, i32 0, ...
11857 //
11858 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11859 // into : GEP i8* X, ...
11860 //
11861 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011862 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011863 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11864 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011865 if (const ArrayType *CATy =
11866 dyn_cast<ArrayType>(CPTy->getElementType())) {
11867 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11868 if (CATy->getElementType() == XTy->getElementType()) {
11869 // -> GEP i8* X, ...
11870 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011871 return cast<GEPOperator>(&GEP)->isInBounds() ?
11872 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11873 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011874 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11875 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011876 }
11877
11878 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011879 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011880 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011881 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011882 // At this point, we know that the cast source type is a pointer
11883 // to an array of the same type as the destination pointer
11884 // array. Because the array type is never stepped over (there
11885 // is a leading zero) we can fold the cast into this GEP.
11886 GEP.setOperand(0, X);
11887 return &GEP;
11888 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011889 }
11890 }
Chris Lattnereed48272005-09-13 00:40:14 +000011891 } else if (GEP.getNumOperands() == 2) {
11892 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011893 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11894 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011895 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11896 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011897 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011898 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11899 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011900 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011901 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011902 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011903 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11904 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011905 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011906 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011907 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011908 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011909
11910 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011911 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011912 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011913 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011914
Owen Anderson1d0be152009-08-13 21:58:54 +000011915 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011916 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011917 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011918
11919 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11920 // allow either a mul, shift, or constant here.
11921 Value *NewIdx = 0;
11922 ConstantInt *Scale = 0;
11923 if (ArrayEltSize == 1) {
11924 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011925 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011926 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011927 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011928 Scale = CI;
11929 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11930 if (Inst->getOpcode() == Instruction::Shl &&
11931 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011932 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11933 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011934 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011935 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011936 NewIdx = Inst->getOperand(0);
11937 } else if (Inst->getOpcode() == Instruction::Mul &&
11938 isa<ConstantInt>(Inst->getOperand(1))) {
11939 Scale = cast<ConstantInt>(Inst->getOperand(1));
11940 NewIdx = Inst->getOperand(0);
11941 }
11942 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011943
Chris Lattner7835cdd2005-09-13 18:36:04 +000011944 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011945 // out, perform the transformation. Note, we don't know whether Scale is
11946 // signed or not. We'll use unsigned version of division/modulo
11947 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011948 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011949 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011950 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011951 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011952 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011953 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11954 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011955 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011956 }
11957
11958 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011959 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011960 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011961 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011962 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11963 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11964 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011965 // The NewGEP must be pointer typed, so must the old one -> BitCast
11966 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011967 }
11968 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011969 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011970 }
Chris Lattner58407792009-01-09 04:53:57 +000011971
Chris Lattner46cd5a12009-01-09 05:44:56 +000011972 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011973 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011974 /// Y = gep X, <...constant indices...>
11975 /// into a gep of the original struct. This is important for SROA and alias
11976 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011977 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011978 if (TD &&
11979 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011980 // Determine how much the GEP moves the pointer. We are guaranteed to get
11981 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011982 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011983 int64_t Offset = OffsetV->getSExtValue();
11984
11985 // If this GEP instruction doesn't move the pointer, just replace the GEP
11986 // with a bitcast of the real input to the dest type.
11987 if (Offset == 0) {
11988 // If the bitcast is of an allocation, and the allocation will be
11989 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011990 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011991 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011992 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11993 if (Instruction *I = visitBitCast(*BCI)) {
11994 if (I != BCI) {
11995 I->takeName(BCI);
11996 BCI->getParent()->getInstList().insert(BCI, I);
11997 ReplaceInstUsesWith(*BCI, I);
11998 }
11999 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000012000 }
Chris Lattner58407792009-01-09 04:53:57 +000012001 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012002 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000012003 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012004
12005 // Otherwise, if the offset is non-zero, we need to find out if there is a
12006 // field at Offset in 'A's type. If so, we can pull the cast through the
12007 // GEP.
12008 SmallVector<Value*, 8> NewIndices;
12009 const Type *InTy =
12010 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000012011 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012012 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12013 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12014 NewIndices.end()) :
12015 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12016 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012017
12018 if (NGEP->getType() == GEP.getType())
12019 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000012020 NGEP->takeName(&GEP);
12021 return new BitCastInst(NGEP, GEP.getType());
12022 }
Chris Lattner58407792009-01-09 04:53:57 +000012023 }
12024 }
12025
Chris Lattner8a2a3112001-12-14 16:52:21 +000012026 return 0;
12027}
12028
Victor Hernandez7b929da2009-10-23 21:09:37 +000012029Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012030 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012031 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012032 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12033 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012034 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012035 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012036 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012037 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012038
Chris Lattner0864acf2002-11-04 16:18:53 +000012039 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012040 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012041 //
12042 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012043 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012044
12045 // Now that I is pointing to the first non-allocation-inst in the block,
12046 // insert our getelementptr instruction...
12047 //
Owen Anderson1d0be152009-08-13 21:58:54 +000012048 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012049 Value *Idx[2];
12050 Idx[0] = NullIdx;
12051 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012052 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12053 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012054
12055 // Now make everything use the getelementptr instead of the original
12056 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012057 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012058 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012059 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012060 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012061 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012062
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012063 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012064 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012065 // Note that we only do this for alloca's, because malloc should allocate
12066 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012067 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012068 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012069
12070 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12071 if (AI.getAlignment() == 0)
12072 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12073 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012074
Chris Lattner0864acf2002-11-04 16:18:53 +000012075 return 0;
12076}
12077
Victor Hernandez66284e02009-10-24 04:23:03 +000012078Instruction *InstCombiner::visitFree(Instruction &FI) {
12079 Value *Op = FI.getOperand(1);
12080
12081 // free undef -> unreachable.
12082 if (isa<UndefValue>(Op)) {
12083 // Insert a new store to null because we cannot modify the CFG here.
12084 new StoreInst(ConstantInt::getTrue(*Context),
12085 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12086 return EraseInstFromFunction(FI);
12087 }
12088
12089 // If we have 'free null' delete the instruction. This can happen in stl code
12090 // when lots of inlining happens.
12091 if (isa<ConstantPointerNull>(Op))
12092 return EraseInstFromFunction(FI);
12093
Victor Hernandez046e78c2009-10-26 23:43:48 +000012094 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012095 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012096 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12097 if (Op->hasOneUse() && CI->hasOneUse()) {
12098 EraseInstFromFunction(FI);
12099 EraseInstFromFunction(*CI);
12100 return EraseInstFromFunction(*cast<Instruction>(Op));
12101 }
12102 } else {
12103 // Op is a call to malloc
12104 if (Op->hasOneUse()) {
12105 EraseInstFromFunction(FI);
12106 return EraseInstFromFunction(*cast<Instruction>(Op));
12107 }
12108 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012109 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012110
12111 return 0;
12112}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012113
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012114/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012115static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012116 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012117 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012118 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000012119 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000012120
Mon P Wang6753f952009-02-07 22:19:29 +000012121 const PointerType *DestTy = cast<PointerType>(CI->getType());
12122 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012123 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012124
12125 // If the address spaces don't match, don't eliminate the cast.
12126 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12127 return 0;
12128
Chris Lattnerb89e0712004-07-13 01:49:43 +000012129 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012130
Reid Spencer42230162007-01-22 05:51:25 +000012131 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012132 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012133 // If the source is an array, the code below will not succeed. Check to
12134 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12135 // constants.
12136 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12137 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12138 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012139 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000012140 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12141 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012142 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012143 SrcTy = cast<PointerType>(CastOp->getType());
12144 SrcPTy = SrcTy->getElementType();
12145 }
12146
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012147 if (IC.getTargetData() &&
12148 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012149 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012150 // Do not allow turning this into a load of an integer, which is then
12151 // casted to a pointer, this pessimizes pointer analysis a lot.
12152 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012153 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12154 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012155
Chris Lattnerf9527852005-01-31 04:50:46 +000012156 // Okay, we are casting from one integer or pointer type to another of
12157 // the same size. Instead of casting the pointer before the load, cast
12158 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012159 Value *NewLoad =
12160 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012161 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012162 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012163 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012164 }
12165 }
12166 return 0;
12167}
12168
Chris Lattner833b8a42003-06-26 05:06:25 +000012169Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12170 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012171
Dan Gohman9941f742007-07-20 16:34:21 +000012172 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012173 if (TD) {
12174 unsigned KnownAlign =
12175 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12176 if (KnownAlign >
12177 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12178 LI.getAlignment()))
12179 LI.setAlignment(KnownAlign);
12180 }
Dan Gohman9941f742007-07-20 16:34:21 +000012181
Chris Lattner963f4ba2009-08-30 20:36:46 +000012182 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012183 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012184 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012185 return Res;
12186
12187 // None of the following transforms are legal for volatile loads.
12188 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012189
Dan Gohman2276a7b2008-10-15 23:19:35 +000012190 // Do really simple store-to-load forwarding and load CSE, to catch cases
12191 // where there are several consequtive memory accesses to the same location,
12192 // separated by a few arithmetic operations.
12193 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012194 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12195 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012196
Chris Lattner878e4942009-10-22 06:25:11 +000012197 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012198 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12199 const Value *GEPI0 = GEPI->getOperand(0);
12200 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012201 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012202 // Insert a new store to null instruction before the load to indicate
12203 // that this code is not reachable. We do this instead of inserting
12204 // an unreachable instruction directly because we cannot modify the
12205 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012206 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012207 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012208 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012209 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012210 }
Chris Lattner37366c12005-05-01 04:24:53 +000012211
Chris Lattner878e4942009-10-22 06:25:11 +000012212 // load null/undef -> unreachable
12213 // TODO: Consider a target hook for valid address spaces for this xform.
12214 if (isa<UndefValue>(Op) ||
12215 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12216 // Insert a new store to null instruction before the load to indicate that
12217 // this code is not reachable. We do this instead of inserting an
12218 // unreachable instruction directly because we cannot modify the CFG.
12219 new StoreInst(UndefValue::get(LI.getType()),
12220 Constant::getNullValue(Op->getType()), &LI);
12221 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012222 }
Chris Lattner878e4942009-10-22 06:25:11 +000012223
12224 // Instcombine load (constantexpr_cast global) -> cast (load global)
12225 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12226 if (CE->isCast())
12227 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12228 return Res;
12229
Chris Lattner37366c12005-05-01 04:24:53 +000012230 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012231 // Change select and PHI nodes to select values instead of addresses: this
12232 // helps alias analysis out a lot, allows many others simplifications, and
12233 // exposes redundancy in the code.
12234 //
12235 // Note that we cannot do the transformation unless we know that the
12236 // introduced loads cannot trap! Something like this is valid as long as
12237 // the condition is always false: load (select bool %C, int* null, int* %G),
12238 // but it would not be valid if we transformed it to load from null
12239 // unconditionally.
12240 //
12241 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12242 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012243 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12244 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012245 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12246 SI->getOperand(1)->getName()+".val");
12247 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12248 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012249 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012250 }
12251
Chris Lattner684fe212004-09-23 15:46:00 +000012252 // load (select (cond, null, P)) -> load P
12253 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12254 if (C->isNullValue()) {
12255 LI.setOperand(0, SI->getOperand(2));
12256 return &LI;
12257 }
12258
12259 // load (select (cond, P, null)) -> load P
12260 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12261 if (C->isNullValue()) {
12262 LI.setOperand(0, SI->getOperand(1));
12263 return &LI;
12264 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012265 }
12266 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012267 return 0;
12268}
12269
Reid Spencer55af2b52007-01-19 21:20:31 +000012270/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012271/// when possible. This makes it generally easy to do alias analysis and/or
12272/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012273static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12274 User *CI = cast<User>(SI.getOperand(1));
12275 Value *CastOp = CI->getOperand(0);
12276
12277 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012278 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12279 if (SrcTy == 0) return 0;
12280
12281 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012282
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012283 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12284 return 0;
12285
Chris Lattner3914f722009-01-24 01:00:13 +000012286 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12287 /// to its first element. This allows us to handle things like:
12288 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12289 /// on 32-bit hosts.
12290 SmallVector<Value*, 4> NewGEPIndices;
12291
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012292 // If the source is an array, the code below will not succeed. Check to
12293 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12294 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012295 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12296 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012297 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012298 NewGEPIndices.push_back(Zero);
12299
12300 while (1) {
12301 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012302 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012303 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012304 NewGEPIndices.push_back(Zero);
12305 SrcPTy = STy->getElementType(0);
12306 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12307 NewGEPIndices.push_back(Zero);
12308 SrcPTy = ATy->getElementType();
12309 } else {
12310 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012311 }
Chris Lattner3914f722009-01-24 01:00:13 +000012312 }
12313
Owen Andersondebcb012009-07-29 22:17:13 +000012314 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012315 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012316
12317 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12318 return 0;
12319
Chris Lattner71759c42009-01-16 20:12:52 +000012320 // If the pointers point into different address spaces or if they point to
12321 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012322 if (!IC.getTargetData() ||
12323 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012324 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012325 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12326 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012327 return 0;
12328
12329 // Okay, we are casting from one integer or pointer type to another of
12330 // the same size. Instead of casting the pointer before
12331 // the store, cast the value to be stored.
12332 Value *NewCast;
12333 Value *SIOp0 = SI.getOperand(0);
12334 Instruction::CastOps opcode = Instruction::BitCast;
12335 const Type* CastSrcTy = SIOp0->getType();
12336 const Type* CastDstTy = SrcPTy;
12337 if (isa<PointerType>(CastDstTy)) {
12338 if (CastSrcTy->isInteger())
12339 opcode = Instruction::IntToPtr;
12340 } else if (isa<IntegerType>(CastDstTy)) {
12341 if (isa<PointerType>(SIOp0->getType()))
12342 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012343 }
Chris Lattner3914f722009-01-24 01:00:13 +000012344
12345 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12346 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012347 if (!NewGEPIndices.empty())
12348 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12349 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012350
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012351 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12352 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012353 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012354}
12355
Chris Lattner4aebaee2008-11-27 08:56:30 +000012356/// equivalentAddressValues - Test if A and B will obviously have the same
12357/// value. This includes recognizing that %t0 and %t1 will have the same
12358/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012359/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012360/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012361/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012362/// %t2 = load i32* %t1
12363///
12364static bool equivalentAddressValues(Value *A, Value *B) {
12365 // Test if the values are trivially equivalent.
12366 if (A == B) return true;
12367
12368 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012369 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12370 // its only used to compare two uses within the same basic block, which
12371 // means that they'll always either have the same value or one of them
12372 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012373 if (isa<BinaryOperator>(A) ||
12374 isa<CastInst>(A) ||
12375 isa<PHINode>(A) ||
12376 isa<GetElementPtrInst>(A))
12377 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012378 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012379 return true;
12380
12381 // Otherwise they may not be equivalent.
12382 return false;
12383}
12384
Dale Johannesen4945c652009-03-03 21:26:39 +000012385// If this instruction has two uses, one of which is a llvm.dbg.declare,
12386// return the llvm.dbg.declare.
12387DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12388 if (!V->hasNUses(2))
12389 return 0;
12390 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12391 UI != E; ++UI) {
12392 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12393 return DI;
12394 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12395 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12396 return DI;
12397 }
12398 }
12399 return 0;
12400}
12401
Chris Lattner2f503e62005-01-31 05:36:43 +000012402Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12403 Value *Val = SI.getOperand(0);
12404 Value *Ptr = SI.getOperand(1);
12405
Chris Lattner836692d2007-01-15 06:51:56 +000012406 // If the RHS is an alloca with a single use, zapify the store, making the
12407 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012408 // If the RHS is an alloca with a two uses, the other one being a
12409 // llvm.dbg.declare, zapify the store and the declare, making the
12410 // alloca dead. We must do this to prevent declare's from affecting
12411 // codegen.
12412 if (!SI.isVolatile()) {
12413 if (Ptr->hasOneUse()) {
12414 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012415 EraseInstFromFunction(SI);
12416 ++NumCombined;
12417 return 0;
12418 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012419 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12420 if (isa<AllocaInst>(GEP->getOperand(0))) {
12421 if (GEP->getOperand(0)->hasOneUse()) {
12422 EraseInstFromFunction(SI);
12423 ++NumCombined;
12424 return 0;
12425 }
12426 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12427 EraseInstFromFunction(*DI);
12428 EraseInstFromFunction(SI);
12429 ++NumCombined;
12430 return 0;
12431 }
12432 }
12433 }
12434 }
12435 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12436 EraseInstFromFunction(*DI);
12437 EraseInstFromFunction(SI);
12438 ++NumCombined;
12439 return 0;
12440 }
Chris Lattner836692d2007-01-15 06:51:56 +000012441 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012442
Dan Gohman9941f742007-07-20 16:34:21 +000012443 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012444 if (TD) {
12445 unsigned KnownAlign =
12446 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12447 if (KnownAlign >
12448 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12449 SI.getAlignment()))
12450 SI.setAlignment(KnownAlign);
12451 }
Dan Gohman9941f742007-07-20 16:34:21 +000012452
Dale Johannesenacb51a32009-03-03 01:43:03 +000012453 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012454 // stores to the same location, separated by a few arithmetic operations. This
12455 // situation often occurs with bitfield accesses.
12456 BasicBlock::iterator BBI = &SI;
12457 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12458 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012459 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012460 // Don't count debug info directives, lest they affect codegen,
12461 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12462 // It is necessary for correctness to skip those that feed into a
12463 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012464 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012465 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012466 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012467 continue;
12468 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012469
12470 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12471 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012472 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12473 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012474 ++NumDeadStore;
12475 ++BBI;
12476 EraseInstFromFunction(*PrevSI);
12477 continue;
12478 }
12479 break;
12480 }
12481
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012482 // If this is a load, we have to stop. However, if the loaded value is from
12483 // the pointer we're loading and is producing the pointer we're storing,
12484 // then *this* store is dead (X = load P; store X -> P).
12485 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012486 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12487 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012488 EraseInstFromFunction(SI);
12489 ++NumCombined;
12490 return 0;
12491 }
12492 // Otherwise, this is a load from some other location. Stores before it
12493 // may not be dead.
12494 break;
12495 }
12496
Chris Lattner9ca96412006-02-08 03:25:32 +000012497 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012498 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012499 break;
12500 }
12501
12502
12503 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012504
12505 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012506 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012507 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012508 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012509 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012510 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012511 ++NumCombined;
12512 }
12513 return 0; // Do not modify these!
12514 }
12515
12516 // store undef, Ptr -> noop
12517 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012518 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012519 ++NumCombined;
12520 return 0;
12521 }
12522
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012523 // If the pointer destination is a cast, see if we can fold the cast into the
12524 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012525 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012526 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12527 return Res;
12528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012529 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012530 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12531 return Res;
12532
Chris Lattner408902b2005-09-12 23:23:25 +000012533
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012534 // If this store is the last instruction in the basic block (possibly
12535 // excepting debug info instructions and the pointer bitcasts that feed
12536 // into them), and if the block ends with an unconditional branch, try
12537 // to move it to the successor block.
12538 BBI = &SI;
12539 do {
12540 ++BBI;
12541 } while (isa<DbgInfoIntrinsic>(BBI) ||
12542 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012543 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012544 if (BI->isUnconditional())
12545 if (SimplifyStoreAtEndOfBlock(SI))
12546 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012547
Chris Lattner2f503e62005-01-31 05:36:43 +000012548 return 0;
12549}
12550
Chris Lattner3284d1f2007-04-15 00:07:55 +000012551/// SimplifyStoreAtEndOfBlock - Turn things like:
12552/// if () { *P = v1; } else { *P = v2 }
12553/// into a phi node with a store in the successor.
12554///
Chris Lattner31755a02007-04-15 01:02:18 +000012555/// Simplify things like:
12556/// *P = v1; if () { *P = v2; }
12557/// into a phi node with a store in the successor.
12558///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012559bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12560 BasicBlock *StoreBB = SI.getParent();
12561
12562 // Check to see if the successor block has exactly two incoming edges. If
12563 // so, see if the other predecessor contains a store to the same location.
12564 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012565 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012566
12567 // Determine whether Dest has exactly two predecessors and, if so, compute
12568 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012569 pred_iterator PI = pred_begin(DestBB);
12570 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012571 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012572 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012573 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012574 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012575 return false;
12576
12577 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012578 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012579 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012580 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012581 }
Chris Lattner31755a02007-04-15 01:02:18 +000012582 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012583 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012584
12585 // Bail out if all the relevant blocks aren't distinct (this can happen,
12586 // for example, if SI is in an infinite loop)
12587 if (StoreBB == DestBB || OtherBB == DestBB)
12588 return false;
12589
Chris Lattner31755a02007-04-15 01:02:18 +000012590 // Verify that the other block ends in a branch and is not otherwise empty.
12591 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012592 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012593 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012594 return false;
12595
Chris Lattner31755a02007-04-15 01:02:18 +000012596 // If the other block ends in an unconditional branch, check for the 'if then
12597 // else' case. there is an instruction before the branch.
12598 StoreInst *OtherStore = 0;
12599 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012600 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012601 // Skip over debugging info.
12602 while (isa<DbgInfoIntrinsic>(BBI) ||
12603 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12604 if (BBI==OtherBB->begin())
12605 return false;
12606 --BBI;
12607 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012608 // If this isn't a store, isn't a store to the same location, or if the
12609 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012610 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012611 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12612 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012613 return false;
12614 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012615 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012616 // destinations is StoreBB, then we have the if/then case.
12617 if (OtherBr->getSuccessor(0) != StoreBB &&
12618 OtherBr->getSuccessor(1) != StoreBB)
12619 return false;
12620
12621 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012622 // if/then triangle. See if there is a store to the same ptr as SI that
12623 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012624 for (;; --BBI) {
12625 // Check to see if we find the matching store.
12626 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012627 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12628 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012629 return false;
12630 break;
12631 }
Eli Friedman6903a242008-06-13 22:02:12 +000012632 // If we find something that may be using or overwriting the stored
12633 // value, or if we run out of instructions, we can't do the xform.
12634 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012635 BBI == OtherBB->begin())
12636 return false;
12637 }
12638
12639 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012640 // make sure nothing reads or overwrites the stored value in
12641 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012642 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12643 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012644 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012645 return false;
12646 }
12647 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012648
Chris Lattner31755a02007-04-15 01:02:18 +000012649 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012650 Value *MergedVal = OtherStore->getOperand(0);
12651 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012652 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012653 PN->reserveOperandSpace(2);
12654 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012655 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12656 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012657 }
12658
12659 // Advance to a place where it is safe to insert the new store and
12660 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012661 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012662 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012663 OtherStore->isVolatile(),
12664 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012665
12666 // Nuke the old stores.
12667 EraseInstFromFunction(SI);
12668 EraseInstFromFunction(*OtherStore);
12669 ++NumCombined;
12670 return true;
12671}
12672
Chris Lattner2f503e62005-01-31 05:36:43 +000012673
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012674Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12675 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012676 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012677 BasicBlock *TrueDest;
12678 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012679 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012680 !isa<Constant>(X)) {
12681 // Swap Destinations and condition...
12682 BI.setCondition(X);
12683 BI.setSuccessor(0, FalseDest);
12684 BI.setSuccessor(1, TrueDest);
12685 return &BI;
12686 }
12687
Reid Spencere4d87aa2006-12-23 06:05:41 +000012688 // Cannonicalize fcmp_one -> fcmp_oeq
12689 FCmpInst::Predicate FPred; Value *Y;
12690 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012691 TrueDest, FalseDest)) &&
12692 BI.getCondition()->hasOneUse())
12693 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12694 FPred == FCmpInst::FCMP_OGE) {
12695 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12696 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12697
12698 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012699 BI.setSuccessor(0, FalseDest);
12700 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012701 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012702 return &BI;
12703 }
12704
12705 // Cannonicalize icmp_ne -> icmp_eq
12706 ICmpInst::Predicate IPred;
12707 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012708 TrueDest, FalseDest)) &&
12709 BI.getCondition()->hasOneUse())
12710 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12711 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12712 IPred == ICmpInst::ICMP_SGE) {
12713 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12714 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12715 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012716 BI.setSuccessor(0, FalseDest);
12717 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012718 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012719 return &BI;
12720 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012721
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012722 return 0;
12723}
Chris Lattner0864acf2002-11-04 16:18:53 +000012724
Chris Lattner46238a62004-07-03 00:26:11 +000012725Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12726 Value *Cond = SI.getCondition();
12727 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12728 if (I->getOpcode() == Instruction::Add)
12729 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12730 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12731 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012732 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012733 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012734 AddRHS));
12735 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012736 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012737 return &SI;
12738 }
12739 }
12740 return 0;
12741}
12742
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012743Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012744 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012745
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012746 if (!EV.hasIndices())
12747 return ReplaceInstUsesWith(EV, Agg);
12748
12749 if (Constant *C = dyn_cast<Constant>(Agg)) {
12750 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012751 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012752
12753 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012754 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012755
12756 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12757 // Extract the element indexed by the first index out of the constant
12758 Value *V = C->getOperand(*EV.idx_begin());
12759 if (EV.getNumIndices() > 1)
12760 // Extract the remaining indices out of the constant indexed by the
12761 // first index
12762 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12763 else
12764 return ReplaceInstUsesWith(EV, V);
12765 }
12766 return 0; // Can't handle other constants
12767 }
12768 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12769 // We're extracting from an insertvalue instruction, compare the indices
12770 const unsigned *exti, *exte, *insi, *inse;
12771 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12772 exte = EV.idx_end(), inse = IV->idx_end();
12773 exti != exte && insi != inse;
12774 ++exti, ++insi) {
12775 if (*insi != *exti)
12776 // The insert and extract both reference distinctly different elements.
12777 // This means the extract is not influenced by the insert, and we can
12778 // replace the aggregate operand of the extract with the aggregate
12779 // operand of the insert. i.e., replace
12780 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12781 // %E = extractvalue { i32, { i32 } } %I, 0
12782 // with
12783 // %E = extractvalue { i32, { i32 } } %A, 0
12784 return ExtractValueInst::Create(IV->getAggregateOperand(),
12785 EV.idx_begin(), EV.idx_end());
12786 }
12787 if (exti == exte && insi == inse)
12788 // Both iterators are at the end: Index lists are identical. Replace
12789 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12790 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12791 // with "i32 42"
12792 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12793 if (exti == exte) {
12794 // The extract list is a prefix of the insert list. i.e. replace
12795 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12796 // %E = extractvalue { i32, { i32 } } %I, 1
12797 // with
12798 // %X = extractvalue { i32, { i32 } } %A, 1
12799 // %E = insertvalue { i32 } %X, i32 42, 0
12800 // by switching the order of the insert and extract (though the
12801 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012802 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12803 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012804 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12805 insi, inse);
12806 }
12807 if (insi == inse)
12808 // The insert list is a prefix of the extract list
12809 // We can simply remove the common indices from the extract and make it
12810 // operate on the inserted value instead of the insertvalue result.
12811 // i.e., replace
12812 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12813 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12814 // with
12815 // %E extractvalue { i32 } { i32 42 }, 0
12816 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12817 exti, exte);
12818 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012819 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12820 // We're extracting from an intrinsic, see if we're the only user, which
12821 // allows us to simplify multiple result intrinsics to simpler things that
12822 // just get one value..
12823 if (II->hasOneUse()) {
12824 // Check if we're grabbing the overflow bit or the result of a 'with
12825 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12826 // and replace it with a traditional binary instruction.
12827 switch (II->getIntrinsicID()) {
12828 case Intrinsic::uadd_with_overflow:
12829 case Intrinsic::sadd_with_overflow:
12830 if (*EV.idx_begin() == 0) { // Normal result.
12831 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12832 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12833 EraseInstFromFunction(*II);
12834 return BinaryOperator::CreateAdd(LHS, RHS);
12835 }
12836 break;
12837 case Intrinsic::usub_with_overflow:
12838 case Intrinsic::ssub_with_overflow:
12839 if (*EV.idx_begin() == 0) { // Normal result.
12840 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12841 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12842 EraseInstFromFunction(*II);
12843 return BinaryOperator::CreateSub(LHS, RHS);
12844 }
12845 break;
12846 case Intrinsic::umul_with_overflow:
12847 case Intrinsic::smul_with_overflow:
12848 if (*EV.idx_begin() == 0) { // Normal result.
12849 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12850 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12851 EraseInstFromFunction(*II);
12852 return BinaryOperator::CreateMul(LHS, RHS);
12853 }
12854 break;
12855 default:
12856 break;
12857 }
12858 }
12859 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012860 // Can't simplify extracts from other values. Note that nested extracts are
12861 // already simplified implicitely by the above (extract ( extract (insert) )
12862 // will be translated into extract ( insert ( extract ) ) first and then just
12863 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012864 return 0;
12865}
12866
Chris Lattner220b0cf2006-03-05 00:22:33 +000012867/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12868/// is to leave as a vector operation.
12869static bool CheapToScalarize(Value *V, bool isConstant) {
12870 if (isa<ConstantAggregateZero>(V))
12871 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012872 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012873 if (isConstant) return true;
12874 // If all elts are the same, we can extract.
12875 Constant *Op0 = C->getOperand(0);
12876 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12877 if (C->getOperand(i) != Op0)
12878 return false;
12879 return true;
12880 }
12881 Instruction *I = dyn_cast<Instruction>(V);
12882 if (!I) return false;
12883
12884 // Insert element gets simplified to the inserted element or is deleted if
12885 // this is constant idx extract element and its a constant idx insertelt.
12886 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12887 isa<ConstantInt>(I->getOperand(2)))
12888 return true;
12889 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12890 return true;
12891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12892 if (BO->hasOneUse() &&
12893 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12894 CheapToScalarize(BO->getOperand(1), isConstant)))
12895 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012896 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12897 if (CI->hasOneUse() &&
12898 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12899 CheapToScalarize(CI->getOperand(1), isConstant)))
12900 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012901
12902 return false;
12903}
12904
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012905/// Read and decode a shufflevector mask.
12906///
12907/// It turns undef elements into values that are larger than the number of
12908/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012909static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12910 unsigned NElts = SVI->getType()->getNumElements();
12911 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12912 return std::vector<unsigned>(NElts, 0);
12913 if (isa<UndefValue>(SVI->getOperand(2)))
12914 return std::vector<unsigned>(NElts, 2*NElts);
12915
12916 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012917 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012918 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12919 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012920 Result.push_back(NElts*2); // undef -> 8
12921 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012922 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012923 return Result;
12924}
12925
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012926/// FindScalarElement - Given a vector and an element number, see if the scalar
12927/// value is already around as a register, for example if it were inserted then
12928/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012929static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012930 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012931 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12932 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012933 unsigned Width = PTy->getNumElements();
12934 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012935 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012936
12937 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012938 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012939 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012940 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012941 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012942 return CP->getOperand(EltNo);
12943 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12944 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012945 if (!isa<ConstantInt>(III->getOperand(2)))
12946 return 0;
12947 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012948
12949 // If this is an insert to the element we are looking for, return the
12950 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012951 if (EltNo == IIElt)
12952 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012953
12954 // Otherwise, the insertelement doesn't modify the value, recurse on its
12955 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012956 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012957 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012958 unsigned LHSWidth =
12959 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012960 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012961 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012962 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012963 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012964 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012965 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012966 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012967 }
12968
12969 // Otherwise, we don't know.
12970 return 0;
12971}
12972
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012973Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012974 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012975 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012976 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012977
Dan Gohman07a96762007-07-16 14:29:03 +000012978 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012979 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012980 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012981
Reid Spencer9d6565a2007-02-15 02:26:10 +000012982 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012983 // If vector val is constant with all elements the same, replace EI with
12984 // that element. When the elements are not identical, we cannot replace yet
12985 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012986 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012987 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012988 if (C->getOperand(i) != op0) {
12989 op0 = 0;
12990 break;
12991 }
12992 if (op0)
12993 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012994 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012995
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012996 // If extracting a specified index from the vector, see if we can recursively
12997 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012998 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012999 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013000 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000013001
13002 // If this is extracting an invalid index, turn this into undef, to avoid
13003 // crashing the code below.
13004 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013005 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000013006
Chris Lattner867b99f2006-10-05 06:55:50 +000013007 // This instruction only demands the single element from the input vector.
13008 // If the input vector has a single use, simplify it based on this use
13009 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000013010 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000013011 APInt UndefElts(VectorWidth, 0);
13012 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000013013 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000013014 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000013015 EI.setOperand(0, V);
13016 return &EI;
13017 }
13018 }
13019
Owen Andersond672ecb2009-07-03 00:17:18 +000013020 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013021 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013022
13023 // If the this extractelement is directly using a bitcast from a vector of
13024 // the same number of elements, see if we can find the source element from
13025 // it. In this case, we will end up needing to bitcast the scalars.
13026 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13027 if (const VectorType *VT =
13028 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13029 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013030 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13031 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013032 return new BitCastInst(Elt, EI.getType());
13033 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013034 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013035
Chris Lattner73fa49d2006-05-25 22:53:38 +000013036 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013037 // Push extractelement into predecessor operation if legal and
13038 // profitable to do so
13039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13040 if (I->hasOneUse() &&
13041 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13042 Value *newEI0 =
13043 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13044 EI.getName()+".lhs");
13045 Value *newEI1 =
13046 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13047 EI.getName()+".rhs");
13048 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013049 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013050 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013051 // Extracting the inserted element?
13052 if (IE->getOperand(2) == EI.getOperand(1))
13053 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13054 // If the inserted and extracted elements are constants, they must not
13055 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013056 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013057 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013058 EI.setOperand(0, IE->getOperand(0));
13059 return &EI;
13060 }
13061 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13062 // If this is extracting an element from a shufflevector, figure out where
13063 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013064 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13065 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013066 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013067 unsigned LHSWidth =
13068 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13069
13070 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013071 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013072 else if (SrcIdx < LHSWidth*2) {
13073 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013074 Src = SVI->getOperand(1);
13075 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013076 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013077 }
Eric Christophera3500da2009-07-25 02:28:41 +000013078 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000013079 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13080 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013081 }
13082 }
Eli Friedman2451a642009-07-18 23:06:53 +000013083 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013084 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013085 return 0;
13086}
13087
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013088/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13089/// elements from either LHS or RHS, return the shuffle mask and true.
13090/// Otherwise, return false.
13091static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000013092 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013093 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013094 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13095 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013096 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013097
13098 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013099 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013100 return true;
13101 } else if (V == LHS) {
13102 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013103 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013104 return true;
13105 } else if (V == RHS) {
13106 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013107 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013108 return true;
13109 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13110 // If this is an insert of an extract from some other vector, include it.
13111 Value *VecOp = IEI->getOperand(0);
13112 Value *ScalarOp = IEI->getOperand(1);
13113 Value *IdxOp = IEI->getOperand(2);
13114
Chris Lattnerd929f062006-04-27 21:14:21 +000013115 if (!isa<ConstantInt>(IdxOp))
13116 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013117 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013118
13119 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13120 // Okay, we can handle this if the vector we are insertinting into is
13121 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013122 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013123 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013124 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000013125 return true;
13126 }
13127 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13128 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013129 EI->getOperand(0)->getType() == V->getType()) {
13130 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013131 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013132
13133 // This must be extracting from either LHS or RHS.
13134 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13135 // Okay, we can handle this if the vector we are insertinting into is
13136 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013137 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013138 // If so, update the mask to reflect the inserted value.
13139 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013140 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013141 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013142 } else {
13143 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013144 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013145 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013146
13147 }
13148 return true;
13149 }
13150 }
13151 }
13152 }
13153 }
13154 // TODO: Handle shufflevector here!
13155
13156 return false;
13157}
13158
13159/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13160/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13161/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013162static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013163 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013164 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013165 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013166 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013167 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013168
13169 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013170 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000013171 return V;
13172 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013173 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013174 return V;
13175 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13176 // If this is an insert of an extract from some other vector, include it.
13177 Value *VecOp = IEI->getOperand(0);
13178 Value *ScalarOp = IEI->getOperand(1);
13179 Value *IdxOp = IEI->getOperand(2);
13180
13181 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13182 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13183 EI->getOperand(0)->getType() == V->getType()) {
13184 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013185 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13186 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013187
13188 // Either the extracted from or inserted into vector must be RHSVec,
13189 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013190 if (EI->getOperand(0) == RHS || RHS == 0) {
13191 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000013192 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013193 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013194 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013195 return V;
13196 }
13197
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013198 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000013199 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13200 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000013201 // Everything but the extracted element is replaced with the RHS.
13202 for (unsigned i = 0; i != NumElts; ++i) {
13203 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000013204 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013205 }
13206 return V;
13207 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013208
13209 // If this insertelement is a chain that comes from exactly these two
13210 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000013211 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13212 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013213 return EI->getOperand(0);
13214
Chris Lattnerefb47352006-04-15 01:39:45 +000013215 }
13216 }
13217 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013218 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013219
13220 // Otherwise, can't do anything fancy. Return an identity vector.
13221 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013222 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013223 return V;
13224}
13225
13226Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13227 Value *VecOp = IE.getOperand(0);
13228 Value *ScalarOp = IE.getOperand(1);
13229 Value *IdxOp = IE.getOperand(2);
13230
Chris Lattner599ded12007-04-09 01:11:16 +000013231 // Inserting an undef or into an undefined place, remove this.
13232 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13233 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013234
Chris Lattnerefb47352006-04-15 01:39:45 +000013235 // If the inserted element was extracted from some other vector, and if the
13236 // indexes are constant, try to turn this into a shufflevector operation.
13237 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13238 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13239 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013240 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013241 unsigned ExtractedIdx =
13242 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013243 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013244
13245 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13246 return ReplaceInstUsesWith(IE, VecOp);
13247
13248 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013249 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013250
13251 // If we are extracting a value from a vector, then inserting it right
13252 // back into the same place, just use the input vector.
13253 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13254 return ReplaceInstUsesWith(IE, VecOp);
13255
Chris Lattnerefb47352006-04-15 01:39:45 +000013256 // If this insertelement isn't used by some other insertelement, turn it
13257 // (and any insertelements it points to), into one big shuffle.
13258 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13259 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013260 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013261 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013262 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013263 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013264 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013265 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013266 }
13267 }
13268 }
13269
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013270 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13271 APInt UndefElts(VWidth, 0);
13272 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13273 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13274 return &IE;
13275
Chris Lattnerefb47352006-04-15 01:39:45 +000013276 return 0;
13277}
13278
13279
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013280Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13281 Value *LHS = SVI.getOperand(0);
13282 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013283 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013284
13285 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013286
Chris Lattner867b99f2006-10-05 06:55:50 +000013287 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013288 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013289 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013290
Dan Gohman488fbfc2008-09-09 18:11:14 +000013291 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013292
13293 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13294 return 0;
13295
Evan Cheng388df622009-02-03 10:05:09 +000013296 APInt UndefElts(VWidth, 0);
13297 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13298 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013299 LHS = SVI.getOperand(0);
13300 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013301 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013302 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013303
Chris Lattner863bcff2006-05-25 23:48:38 +000013304 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13305 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13306 if (LHS == RHS || isa<UndefValue>(LHS)) {
13307 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013308 // shuffle(undef,undef,mask) -> undef.
13309 return ReplaceInstUsesWith(SVI, LHS);
13310 }
13311
Chris Lattner863bcff2006-05-25 23:48:38 +000013312 // Remap any references to RHS to use LHS.
13313 std::vector<Constant*> Elts;
13314 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013315 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013316 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013317 else {
13318 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013319 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013320 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013321 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013322 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013323 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013324 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013325 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013326 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013327 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013328 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013329 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013330 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013331 LHS = SVI.getOperand(0);
13332 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013333 MadeChange = true;
13334 }
13335
Chris Lattner7b2e27922006-05-26 00:29:06 +000013336 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013337 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013338
Chris Lattner863bcff2006-05-25 23:48:38 +000013339 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13340 if (Mask[i] >= e*2) continue; // Ignore undef values.
13341 // Is this an identity shuffle of the LHS value?
13342 isLHSID &= (Mask[i] == i);
13343
13344 // Is this an identity shuffle of the RHS value?
13345 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013346 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013347
Chris Lattner863bcff2006-05-25 23:48:38 +000013348 // Eliminate identity shuffles.
13349 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13350 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013351
Chris Lattner7b2e27922006-05-26 00:29:06 +000013352 // If the LHS is a shufflevector itself, see if we can combine it with this
13353 // one without producing an unusual shuffle. Here we are really conservative:
13354 // we are absolutely afraid of producing a shuffle mask not in the input
13355 // program, because the code gen may not be smart enough to turn a merged
13356 // shuffle into two specific shuffles: it may produce worse code. As such,
13357 // we only merge two shuffles if the result is one of the two input shuffle
13358 // masks. In this case, merging the shuffles just removes one instruction,
13359 // which we know is safe. This is good for things like turning:
13360 // (splat(splat)) -> splat.
13361 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13362 if (isa<UndefValue>(RHS)) {
13363 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13364
David Greenef941d292009-11-16 21:52:23 +000013365 if (LHSMask.size() == Mask.size()) {
13366 std::vector<unsigned> NewMask;
13367 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013368 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013369 NewMask.push_back(2*e);
13370 else
13371 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013372
David Greenef941d292009-11-16 21:52:23 +000013373 // If the result mask is equal to the src shuffle or this
13374 // shuffle mask, do the replacement.
13375 if (NewMask == LHSMask || NewMask == Mask) {
13376 unsigned LHSInNElts =
13377 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13378 getNumElements();
13379 std::vector<Constant*> Elts;
13380 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13381 if (NewMask[i] >= LHSInNElts*2) {
13382 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13383 } else {
13384 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13385 NewMask[i]));
13386 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013387 }
David Greenef941d292009-11-16 21:52:23 +000013388 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13389 LHSSVI->getOperand(1),
13390 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013391 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013392 }
13393 }
13394 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013395
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013396 return MadeChange ? &SVI : 0;
13397}
13398
13399
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013400
Chris Lattnerea1c4542004-12-08 23:43:58 +000013401
13402/// TryToSinkInstruction - Try to move the specified instruction from its
13403/// current block into the beginning of DestBlock, which can only happen if it's
13404/// safe to move the instruction past all of the instructions between it and the
13405/// end of its block.
13406static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13407 assert(I->hasOneUse() && "Invariants didn't hold!");
13408
Chris Lattner108e9022005-10-27 17:13:11 +000013409 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013410 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013411 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013412
Chris Lattnerea1c4542004-12-08 23:43:58 +000013413 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013414 if (isa<AllocaInst>(I) && I->getParent() ==
13415 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013416 return false;
13417
Chris Lattner96a52a62004-12-09 07:14:34 +000013418 // We can only sink load instructions if there is nothing between the load and
13419 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013420 if (I->mayReadFromMemory()) {
13421 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013422 Scan != E; ++Scan)
13423 if (Scan->mayWriteToMemory())
13424 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013425 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013426
Dan Gohman02dea8b2008-05-23 21:05:58 +000013427 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013428
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013429 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013430 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013431 ++NumSunkInst;
13432 return true;
13433}
13434
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013435
13436/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13437/// all reachable code to the worklist.
13438///
13439/// This has a couple of tricks to make the code faster and more powerful. In
13440/// particular, we constant fold and DCE instructions as we go, to avoid adding
13441/// them to the worklist (this significantly speeds up instcombine on code where
13442/// many instructions are dead or constant). Additionally, if we find a branch
13443/// whose condition is a known constant, we only visit the reachable successors.
13444///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013445static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013446 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013447 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013448 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013449 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013450 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013451 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013452
13453 std::vector<Instruction*> InstrsForInstCombineWorklist;
13454 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013455
Chris Lattner2ee743b2009-10-15 04:59:28 +000013456 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13457
Chris Lattner2c7718a2007-03-23 19:17:18 +000013458 while (!Worklist.empty()) {
13459 BB = Worklist.back();
13460 Worklist.pop_back();
13461
13462 // We have now visited this block! If we've already been here, ignore it.
13463 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013464
Chris Lattner2c7718a2007-03-23 19:17:18 +000013465 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13466 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013467
Chris Lattner2c7718a2007-03-23 19:17:18 +000013468 // DCE instruction if trivially dead.
13469 if (isInstructionTriviallyDead(Inst)) {
13470 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013471 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013472 Inst->eraseFromParent();
13473 continue;
13474 }
13475
13476 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013477 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013478 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013479 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13480 << *Inst << '\n');
13481 Inst->replaceAllUsesWith(C);
13482 ++NumConstProp;
13483 Inst->eraseFromParent();
13484 continue;
13485 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013486
13487
13488
13489 if (TD) {
13490 // See if we can constant fold its operands.
13491 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13492 i != e; ++i) {
13493 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13494 if (CE == 0) continue;
13495
13496 // If we already folded this constant, don't try again.
13497 if (!FoldedConstants.insert(CE))
13498 continue;
13499
Chris Lattner7b550cc2009-11-06 04:27:31 +000013500 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013501 if (NewC && NewC != CE) {
13502 *i = NewC;
13503 MadeIRChange = true;
13504 }
13505 }
13506 }
13507
Devang Patel7fe1dec2008-11-19 18:56:50 +000013508
Chris Lattner67f7d542009-10-12 03:58:40 +000013509 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013510 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013511
13512 // Recursively visit successors. If this is a branch or switch on a
13513 // constant, only visit the reachable successor.
13514 TerminatorInst *TI = BB->getTerminator();
13515 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13516 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13517 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013518 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013519 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013520 continue;
13521 }
13522 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13523 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13524 // See if this is an explicit destination.
13525 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13526 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013527 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013528 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013529 continue;
13530 }
13531
13532 // Otherwise it is the default destination.
13533 Worklist.push_back(SI->getSuccessor(0));
13534 continue;
13535 }
13536 }
13537
13538 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13539 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013540 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013541
13542 // Once we've found all of the instructions to add to instcombine's worklist,
13543 // add them in reverse order. This way instcombine will visit from the top
13544 // of the function down. This jives well with the way that it adds all uses
13545 // of instructions to the worklist after doing a transformation, thus avoiding
13546 // some N^2 behavior in pathological cases.
13547 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13548 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013549
13550 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013551}
13552
Chris Lattnerec9c3582007-03-03 02:04:50 +000013553bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013554 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013555
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013556 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13557 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013558
Chris Lattnerb3d59702005-07-07 20:40:38 +000013559 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013560 // Do a depth-first traversal of the function, populate the worklist with
13561 // the reachable instructions. Ignore blocks that are not reachable. Keep
13562 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013563 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013564 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013565
Chris Lattnerb3d59702005-07-07 20:40:38 +000013566 // Do a quick scan over the function. If we find any blocks that are
13567 // unreachable, remove any instructions inside of them. This prevents
13568 // the instcombine code from having to deal with some bad special cases.
13569 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13570 if (!Visited.count(BB)) {
13571 Instruction *Term = BB->getTerminator();
13572 while (Term != BB->begin()) { // Remove instrs bottom-up
13573 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013574
Chris Lattnerbdff5482009-08-23 04:37:46 +000013575 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013576 // A debug intrinsic shouldn't force another iteration if we weren't
13577 // going to do one without it.
13578 if (!isa<DbgInfoIntrinsic>(I)) {
13579 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013580 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013581 }
Devang Patel228ebd02009-10-13 22:56:32 +000013582
Devang Patel228ebd02009-10-13 22:56:32 +000013583 // If I is not void type then replaceAllUsesWith undef.
13584 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013585 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013586 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013587 I->eraseFromParent();
13588 }
13589 }
13590 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013591
Chris Lattner873ff012009-08-30 05:55:36 +000013592 while (!Worklist.isEmpty()) {
13593 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013594 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013595
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013596 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013597 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013598 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013599 EraseInstFromFunction(*I);
13600 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013601 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013602 continue;
13603 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013604
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013605 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013606 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013607 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013608 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013609
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013610 // Add operands to the worklist.
13611 ReplaceInstUsesWith(*I, C);
13612 ++NumConstProp;
13613 EraseInstFromFunction(*I);
13614 MadeIRChange = true;
13615 continue;
13616 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013617
Chris Lattnerea1c4542004-12-08 23:43:58 +000013618 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013619 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013620 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013621 Instruction *UserInst = cast<Instruction>(I->use_back());
13622 BasicBlock *UserParent;
13623
13624 // Get the block the use occurs in.
13625 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13626 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13627 else
13628 UserParent = UserInst->getParent();
13629
Chris Lattnerea1c4542004-12-08 23:43:58 +000013630 if (UserParent != BB) {
13631 bool UserIsSuccessor = false;
13632 // See if the user is one of our successors.
13633 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13634 if (*SI == UserParent) {
13635 UserIsSuccessor = true;
13636 break;
13637 }
13638
13639 // If the user is one of our immediate successors, and if that successor
13640 // only has us as a predecessors (we'd have to split the critical edge
13641 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013642 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013643 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013644 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013645 }
13646 }
13647
Chris Lattner74381062009-08-30 07:44:24 +000013648 // Now that we have an instruction, try combining it to simplify it.
13649 Builder->SetInsertPoint(I->getParent(), I);
13650
Reid Spencera9b81012007-03-26 17:44:01 +000013651#ifndef NDEBUG
13652 std::string OrigI;
13653#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013654 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013655 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13656
Chris Lattner90ac28c2002-08-02 19:29:35 +000013657 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013658 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013659 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013660 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013661 DEBUG(errs() << "IC: Old = " << *I << '\n'
13662 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013663
Chris Lattnerf523d062004-06-09 05:08:07 +000013664 // Everything uses the new instruction now.
13665 I->replaceAllUsesWith(Result);
13666
13667 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013668 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013669 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013670
Chris Lattner6934a042007-02-11 01:23:03 +000013671 // Move the name to the new instruction first.
13672 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013673
13674 // Insert the new instruction into the basic block...
13675 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013676 BasicBlock::iterator InsertPos = I;
13677
13678 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13679 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13680 ++InsertPos;
13681
13682 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013683
Chris Lattner7a1e9242009-08-30 06:13:40 +000013684 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013685 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013686#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013687 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13688 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013689#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013690
Chris Lattner90ac28c2002-08-02 19:29:35 +000013691 // If the instruction was modified, it's possible that it is now dead.
13692 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013693 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013694 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013695 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013696 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013697 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013698 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013699 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013700 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013701 }
13702 }
13703
Chris Lattner873ff012009-08-30 05:55:36 +000013704 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013705 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013706}
13707
Chris Lattnerec9c3582007-03-03 02:04:50 +000013708
13709bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013710 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013711 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013712 TD = getAnalysisIfAvailable<TargetData>();
13713
Chris Lattner74381062009-08-30 07:44:24 +000013714
13715 /// Builder - This is an IRBuilder that automatically inserts new
13716 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013717 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013718 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013719 InstCombineIRInserter(Worklist));
13720 Builder = &TheBuilder;
13721
Chris Lattnerec9c3582007-03-03 02:04:50 +000013722 bool EverMadeChange = false;
13723
13724 // Iterate while there is work to do.
13725 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013726 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013727 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013728
13729 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013730 return EverMadeChange;
13731}
13732
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013733FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013734 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013735}