blob: b4bb0a849d7edb1ed70b53b87d49e621d29d2418 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000055#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000056#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000058#include "llvm/Support/Compiler.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000059#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000060#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000061#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000062#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000064#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000065#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000066#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
95 }
96
Chris Lattner3c4e38e2009-08-30 06:27:41 +000097 void AddValue(Value *V) {
98 if (Instruction *I = dyn_cast<Instruction>(V))
99 Add(I);
100 }
101
Chris Lattner7a1e9242009-08-30 06:13:40 +0000102 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000103 void Remove(Instruction *I) {
104 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105 if (It == WorklistMap.end()) return; // Not in worklist.
106
107 // Don't bother moving everything down, just null out the slot.
108 Worklist[It->second] = 0;
109
110 WorklistMap.erase(It);
111 }
112
113 Instruction *RemoveOne() {
114 Instruction *I = Worklist.back();
115 Worklist.pop_back();
116 WorklistMap.erase(I);
117 return I;
118 }
119
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000120 /// AddUsersToWorkList - When an instruction is simplified, add all users of
121 /// the instruction to the work lists because they might get more simplified
122 /// now.
123 ///
124 void AddUsersToWorkList(Instruction &I) {
125 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126 UI != UE; ++UI)
127 Add(cast<Instruction>(*UI));
128 }
129
Chris Lattner873ff012009-08-30 05:55:36 +0000130
131 /// Zap - check that the worklist is empty and nuke the backing store for
132 /// the map if it is large.
133 void Zap() {
134 assert(WorklistMap.empty() && "Worklist empty, but map not?");
135
136 // Do an explicit clear, this shrinks the map if needed.
137 WorklistMap.clear();
138 }
139 };
140} // end anonymous namespace.
141
142
143namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000144 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145 /// just like the normal insertion helper, but also adds any new instructions
146 /// to the instcombine worklist.
147 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148 InstCombineWorklist &Worklist;
149 public:
150 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
151
152 void InsertHelper(Instruction *I, const Twine &Name,
153 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
155 Worklist.Add(I);
156 }
157 };
158} // end anonymous namespace
159
160
161namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +0000162 class VISIBILITY_HIDDEN InstCombiner
163 : public FunctionPass,
164 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000165 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000166 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000167 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000168 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000169 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000170 InstCombineWorklist Worklist;
171
Chris Lattner74381062009-08-30 07:44:24 +0000172 /// Builder - This is an IRBuilder that automatically inserts new
173 /// instructions into the worklist when they are created.
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000174 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
175 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000176
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000177 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000178 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000179
Owen Andersone922c022009-07-22 00:24:57 +0000180 LLVMContext *Context;
181 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000182
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000183 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000184 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000185
186 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000187
Chris Lattner97e52e42002-04-28 21:27:06 +0000188 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000189 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000190 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000191 }
192
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000193 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000194
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000195 // Visitation implementation - Implement instruction combining for different
196 // instruction types. The semantics are as follows:
197 // Return Value:
198 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000199 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000200 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000201 //
Chris Lattner7e708292002-06-25 16:13:24 +0000202 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000203 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000204 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000205 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000206 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000207 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000208 Instruction *visitURem(BinaryOperator &I);
209 Instruction *visitSRem(BinaryOperator &I);
210 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000211 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000212 Instruction *commonRemTransforms(BinaryOperator &I);
213 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000214 Instruction *commonDivTransforms(BinaryOperator &I);
215 Instruction *commonIDivTransforms(BinaryOperator &I);
216 Instruction *visitUDiv(BinaryOperator &I);
217 Instruction *visitSDiv(BinaryOperator &I);
218 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000219 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000220 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000222 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000223 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000224 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000225 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000226 Instruction *visitOr (BinaryOperator &I);
227 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000228 Instruction *visitShl(BinaryOperator &I);
229 Instruction *visitAShr(BinaryOperator &I);
230 Instruction *visitLShr(BinaryOperator &I);
231 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000232 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
233 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000234 Instruction *visitFCmpInst(FCmpInst &I);
235 Instruction *visitICmpInst(ICmpInst &I);
236 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000237 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
238 Instruction *LHS,
239 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000240 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
241 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000242
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000243 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000244 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000245 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000246 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000247 Instruction *commonCastTransforms(CastInst &CI);
248 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000249 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000250 Instruction *visitTrunc(TruncInst &CI);
251 Instruction *visitZExt(ZExtInst &CI);
252 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000253 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000254 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000255 Instruction *visitFPToUI(FPToUIInst &FI);
256 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000257 Instruction *visitUIToFP(CastInst &CI);
258 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000259 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000260 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000261 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000262 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
263 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000264 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000265 Instruction *visitSelectInst(SelectInst &SI);
266 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000267 Instruction *visitCallInst(CallInst &CI);
268 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000269 Instruction *visitPHINode(PHINode &PN);
270 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000271 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000272 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000273 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000274 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000275 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000276 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000277 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000278 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000279 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000280 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000281
282 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000283 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000284
Chris Lattner9fe38862003-06-19 17:00:31 +0000285 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000286 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000287 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000288 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000289 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000291 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000292 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
293
Chris Lattner9fe38862003-06-19 17:00:31 +0000294
Chris Lattner28977af2004-04-05 01:30:19 +0000295 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000296 // InsertNewInstBefore - insert an instruction New before instruction Old
297 // in the program. Add the new instruction to the worklist.
298 //
Chris Lattner955f3312004-09-28 21:48:02 +0000299 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000300 assert(New && New->getParent() == 0 &&
301 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000302 BasicBlock *BB = Old.getParent();
303 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000304 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000305 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000306 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000307
Chris Lattner8b170942002-08-09 23:47:40 +0000308 // ReplaceInstUsesWith - This method is to be used when an instruction is
309 // found to be dead, replacable with another preexisting expression. Here
310 // we add all uses of I to the worklist, replace all uses of I with the new
311 // value, then return I, so that the inst combiner will know that I was
312 // modified.
313 //
314 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000315 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000316
317 // If we are replacing the instruction with itself, this must be in a
318 // segment of unreachable code, so just clobber the instruction.
319 if (&I == V)
320 V = UndefValue::get(I.getType());
321
322 I.replaceAllUsesWith(V);
323 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000324 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325
326 // EraseInstFromFunction - When dealing with an instruction that has side
327 // effects or produces a void value, we can't rely on DCE to delete the
328 // instruction. Instead, visit methods should return the value returned by
329 // this function.
330 Instruction *EraseInstFromFunction(Instruction &I) {
Chris Lattner931f8f32009-08-31 05:17:58 +0000331 DEBUG(errs() << "IC: erase " << I);
332
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000333 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000334 // Make sure that we reprocess all operands now that we reduced their
335 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000336 if (I.getNumOperands() < 8) {
337 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
338 if (Instruction *Op = dyn_cast<Instruction>(*i))
339 Worklist.Add(Op);
340 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000341 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000342 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000343 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344 return 0; // Don't do anything with FI
345 }
Chris Lattner173234a2008-06-02 01:18:21 +0000346
347 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
348 APInt &KnownOne, unsigned Depth = 0) const {
349 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
350 }
351
352 bool MaskedValueIsZero(Value *V, const APInt &Mask,
353 unsigned Depth = 0) const {
354 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
355 }
356 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
357 return llvm::ComputeNumSignBits(Op, TD, Depth);
358 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000359
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000360 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000361
Reid Spencere4d87aa2006-12-23 06:05:41 +0000362 /// SimplifyCommutative - This performs a few simplifications for
363 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000364 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000365
Reid Spencere4d87aa2006-12-23 06:05:41 +0000366 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
367 /// most-complex to least-complex order.
368 bool SimplifyCompare(CmpInst &I);
369
Chris Lattner886ab6c2009-01-31 08:15:18 +0000370 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
371 /// based on the demanded bits.
372 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
373 APInt& KnownZero, APInt& KnownOne,
374 unsigned Depth);
375 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000376 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000377 unsigned Depth=0);
378
379 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
380 /// SimplifyDemandedBits knows about. See if the instruction has any
381 /// properties that allow us to simplify its operands.
382 bool SimplifyDemandedInstructionBits(Instruction &Inst);
383
Evan Cheng388df622009-02-03 10:05:09 +0000384 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
385 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000386
Chris Lattner4e998b22004-09-29 05:07:12 +0000387 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
388 // PHI node as operand #0, see if we can fold the instruction into the PHI
389 // (which is only possible if all operands to the PHI are constants).
390 Instruction *FoldOpIntoPhi(Instruction &I);
391
Chris Lattnerbac32862004-11-14 19:13:23 +0000392 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
393 // operator and they all are only used by the PHI, PHI together their
394 // inputs, and do the operation once, to the result of the PHI.
395 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000396 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000397 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
398
Chris Lattner7da52b22006-11-01 04:51:18 +0000399
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000400 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
401 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000402
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000403 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000404 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000405 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000406 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000407 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000408 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000409 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000410 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000411 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000412
Chris Lattnerafe91a52006-06-15 19:07:26 +0000413
Reid Spencerc55b2432006-12-13 18:21:21 +0000414 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000415
Dan Gohman6de29f82009-06-15 22:12:54 +0000416 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000417 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000418 unsigned GetOrEnforceKnownAlignment(Value *V,
419 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000420
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000421 };
Chris Lattner873ff012009-08-30 05:55:36 +0000422} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000423
Dan Gohman844731a2008-05-13 00:00:25 +0000424char InstCombiner::ID = 0;
425static RegisterPass<InstCombiner>
426X("instcombine", "Combine redundant instructions");
427
Chris Lattner4f98c562003-03-10 21:43:22 +0000428// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000429// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000430static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000431 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000432 if (BinaryOperator::isNeg(V) ||
433 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000434 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000435 return 3;
436 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000437 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000438 if (isa<Argument>(V)) return 3;
439 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000440}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000441
Chris Lattnerc8802d22003-03-11 00:12:48 +0000442// isOnlyUse - Return true if this instruction will be deleted if we stop using
443// it.
444static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000445 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000446}
447
Chris Lattner4cb170c2004-02-23 06:38:22 +0000448// getPromotedType - Return the specified type promoted as it would be to pass
449// though a va_arg area...
450static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000451 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
452 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000453 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000454 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000455 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000456}
457
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000458/// getBitCastOperand - If the specified operand is a CastInst, a constant
459/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
460/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000461static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000462 if (Operator *O = dyn_cast<Operator>(V)) {
463 if (O->getOpcode() == Instruction::BitCast)
464 return O->getOperand(0);
465 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
466 if (GEP->hasAllZeroIndices())
467 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000468 }
Chris Lattnereed48272005-09-13 00:40:14 +0000469 return 0;
470}
471
Reid Spencer3da59db2006-11-27 01:05:10 +0000472/// This function is a wrapper around CastInst::isEliminableCastPair. It
473/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000474static Instruction::CastOps
475isEliminableCastPair(
476 const CastInst *CI, ///< The first cast instruction
477 unsigned opcode, ///< The opcode of the second cast instruction
478 const Type *DstTy, ///< The target type for the second cast instruction
479 TargetData *TD ///< The target data for pointer size
480) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000481
Reid Spencer3da59db2006-11-27 01:05:10 +0000482 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
483 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000484
Reid Spencer3da59db2006-11-27 01:05:10 +0000485 // Get the opcodes of the two Cast instructions
486 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
487 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000488
Chris Lattnera0e69692009-03-24 18:35:40 +0000489 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000490 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000492
493 // We don't want to form an inttoptr or ptrtoint that converts to an integer
494 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000495 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000496 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000497 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000498 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000499 Res = 0;
500
501 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000502}
503
504/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
505/// in any code being generated. It does not require codegen if V is simple
506/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000507static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
508 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000509 if (V->getType() == Ty || isa<Constant>(V)) return false;
510
Chris Lattner01575b72006-05-25 23:24:33 +0000511 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000512 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000513 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000514 return false;
515 return true;
516}
517
Chris Lattner4f98c562003-03-10 21:43:22 +0000518// SimplifyCommutative - This performs a few simplifications for commutative
519// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000520//
Chris Lattner4f98c562003-03-10 21:43:22 +0000521// 1. Order operands such that they are listed from right (least complex) to
522// left (most complex). This puts constants before unary operators before
523// binary operators.
524//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
526// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000527//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000528bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000530 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000531 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000532
Chris Lattner4f98c562003-03-10 21:43:22 +0000533 if (!I.isAssociative()) return Changed;
534 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
536 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
537 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000538 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000539 cast<Constant>(I.getOperand(1)),
540 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541 I.setOperand(0, Op->getOperand(0));
542 I.setOperand(1, Folded);
543 return true;
544 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
545 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
546 isOnlyUse(Op) && isOnlyUse(Op1)) {
547 Constant *C1 = cast<Constant>(Op->getOperand(1));
548 Constant *C2 = cast<Constant>(Op1->getOperand(1));
549
550 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000551 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000552 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553 Op1->getOperand(0),
554 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000555 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 I.setOperand(0, New);
557 I.setOperand(1, Folded);
558 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000559 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000560 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000561 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000562}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000563
Reid Spencere4d87aa2006-12-23 06:05:41 +0000564/// SimplifyCompare - For a CmpInst this function just orders the operands
565/// so that theyare listed from right (least complex) to left (most complex).
566/// This puts constants before unary operators before binary operators.
567bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000568 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000569 return false;
570 I.swapOperands();
571 // Compare instructions are not associative so there's nothing else we can do.
572 return true;
573}
574
Chris Lattner8d969642003-03-10 23:06:50 +0000575// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
576// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000577//
Dan Gohman186a6362009-08-12 16:04:34 +0000578static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000579 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000580 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000581
Chris Lattner0ce85802004-12-14 20:08:06 +0000582 // Constants can be considered to be negated values if they can be folded.
583 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000584 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000585
586 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
587 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000589
Chris Lattner8d969642003-03-10 23:06:50 +0000590 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000591}
592
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000593// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
594// instruction if the LHS is a constant negative zero (which is the 'negate'
595// form).
596//
Dan Gohman186a6362009-08-12 16:04:34 +0000597static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000598 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000599 return BinaryOperator::getFNegArgument(V);
600
601 // Constants can be considered to be negated values if they can be folded.
602 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000603 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000604
605 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
606 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000607 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000608
609 return 0;
610}
611
Dan Gohman186a6362009-08-12 16:04:34 +0000612static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000613 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000614 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000615
616 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000617 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000618 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000619 return 0;
620}
621
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622// dyn_castFoldableMul - If this value is a multiply that can be folded into
623// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000624// non-constant operand of the multiply, and set CST to point to the multiplier.
625// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000626//
Dan Gohman186a6362009-08-12 16:04:34 +0000627static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000628 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000630 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000631 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000632 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000633 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000634 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000635 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000636 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000637 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000638 CST = ConstantInt::get(V->getType()->getContext(),
639 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000640 return I->getOperand(0);
641 }
642 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000643 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000644}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000645
Reid Spencer7177c3a2007-03-25 05:33:51 +0000646/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000647static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000648 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000649 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000650}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000651/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000652static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000653 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000654 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000655}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000656/// MultiplyOverflows - True if the multiply can not be expressed in an int
657/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000658static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000659 uint32_t W = C1->getBitWidth();
660 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
661 if (sign) {
662 LHSExt.sext(W * 2);
663 RHSExt.sext(W * 2);
664 } else {
665 LHSExt.zext(W * 2);
666 RHSExt.zext(W * 2);
667 }
668
669 APInt MulExt = LHSExt * RHSExt;
670
671 if (sign) {
672 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
673 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
674 return MulExt.slt(Min) || MulExt.sgt(Max);
675 } else
676 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
677}
Chris Lattner955f3312004-09-28 21:48:02 +0000678
Reid Spencere7816b52007-03-08 01:52:58 +0000679
Chris Lattner255d8912006-02-11 09:31:47 +0000680/// ShrinkDemandedConstant - Check to see if the specified operand of the
681/// specified instruction is a constant integer. If so, check to see if there
682/// are any bits set in the constant that are not demanded. If so, shrink the
683/// constant and return true.
684static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000685 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000686 assert(I && "No instruction?");
687 assert(OpNo < I->getNumOperands() && "Operand index too large");
688
689 // If the operand is not a constant integer, nothing to do.
690 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
691 if (!OpC) return false;
692
693 // If there are no bits set that aren't demanded, nothing to do.
694 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
695 if ((~Demanded & OpC->getValue()) == 0)
696 return false;
697
698 // This instruction is producing bits that are not demanded. Shrink the RHS.
699 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000700 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000701 return true;
702}
703
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000704// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
705// set of known zero and one bits, compute the maximum and minimum values that
706// could have the specified known zero and known one bits, returning them in
707// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000708static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000709 const APInt& KnownOne,
710 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000711 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
712 KnownZero.getBitWidth() == Min.getBitWidth() &&
713 KnownZero.getBitWidth() == Max.getBitWidth() &&
714 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000715 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000716
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718 // bit if it is unknown.
719 Min = KnownOne;
720 Max = KnownOne|UnknownBits;
721
Dan Gohman1c8491e2009-04-25 17:12:48 +0000722 if (UnknownBits.isNegative()) { // Sign bit is unknown
723 Min.set(Min.getBitWidth()-1);
724 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726}
727
728// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729// a set of known zero and one bits, compute the maximum and minimum values that
730// could have the specified known zero and known one bits, returning them in
731// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000732static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000733 const APInt &KnownOne,
734 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000735 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
736 KnownZero.getBitWidth() == Min.getBitWidth() &&
737 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000738 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000739 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000740
741 // The minimum value is when the unknown bits are all zeros.
742 Min = KnownOne;
743 // The maximum value is when the unknown bits are all ones.
744 Max = KnownOne|UnknownBits;
745}
Chris Lattner255d8912006-02-11 09:31:47 +0000746
Chris Lattner886ab6c2009-01-31 08:15:18 +0000747/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
748/// SimplifyDemandedBits knows about. See if the instruction has any
749/// properties that allow us to simplify its operands.
750bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000751 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000752 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
753 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
754
755 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
756 KnownZero, KnownOne, 0);
757 if (V == 0) return false;
758 if (V == &Inst) return true;
759 ReplaceInstUsesWith(Inst, V);
760 return true;
761}
762
763/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
764/// specified instruction operand if possible, updating it in place. It returns
765/// true if it made any change and false otherwise.
766bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
767 APInt &KnownZero, APInt &KnownOne,
768 unsigned Depth) {
769 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
770 KnownZero, KnownOne, Depth);
771 if (NewVal == 0) return false;
772 U.set(NewVal);
773 return true;
774}
775
776
777/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
778/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000779/// that only the bits set in DemandedMask of the result of V are ever used
780/// downstream. Consequently, depending on the mask and V, it may be possible
781/// to replace V with a constant or one of its operands. In such cases, this
782/// function does the replacement and returns true. In all other cases, it
783/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000784/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000785/// to be zero in the expression. These are provided to potentially allow the
786/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
787/// the expression. KnownOne and KnownZero always follow the invariant that
788/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
789/// the bits in KnownOne and KnownZero may only be accurate for those bits set
790/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
791/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000792///
793/// This returns null if it did not change anything and it permits no
794/// simplification. This returns V itself if it did some simplification of V's
795/// operands based on the information about what bits are demanded. This returns
796/// some other non-null value if it found out that V is equal to another value
797/// in the context where the specified bits are demanded, but not for all users.
798Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
799 APInt &KnownZero, APInt &KnownOne,
800 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000801 assert(V != 0 && "Null pointer of Value???");
802 assert(Depth <= 6 && "Limit Search Depth");
803 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000804 const Type *VTy = V->getType();
805 assert((TD || !isa<PointerType>(VTy)) &&
806 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000807 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
808 (!VTy->isIntOrIntVector() ||
809 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000810 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000811 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000812 "Value *V, DemandedMask, KnownZero and KnownOne "
813 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000814 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
815 // We know all of the bits for a constant!
816 KnownOne = CI->getValue() & DemandedMask;
817 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000818 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000819 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000820 if (isa<ConstantPointerNull>(V)) {
821 // We know all of the bits for a constant!
822 KnownOne.clear();
823 KnownZero = DemandedMask;
824 return 0;
825 }
826
Chris Lattner08d2cc72009-01-31 07:26:06 +0000827 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000828 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000829 if (DemandedMask == 0) { // Not demanding any bits from V.
830 if (isa<UndefValue>(V))
831 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000832 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000833 }
834
Chris Lattner4598c942009-01-31 08:24:16 +0000835 if (Depth == 6) // Limit search depth.
836 return 0;
837
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000838 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
839 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
840
Dan Gohman1c8491e2009-04-25 17:12:48 +0000841 Instruction *I = dyn_cast<Instruction>(V);
842 if (!I) {
843 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
844 return 0; // Only analyze instructions.
845 }
846
Chris Lattner4598c942009-01-31 08:24:16 +0000847 // If there are multiple uses of this value and we aren't at the root, then
848 // we can't do any simplifications of the operands, because DemandedMask
849 // only reflects the bits demanded by *one* of the users.
850 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000851 // Despite the fact that we can't simplify this instruction in all User's
852 // context, we can at least compute the knownzero/knownone bits, and we can
853 // do simplifications that apply to *just* the one user if we know that
854 // this instruction has a simpler value in that context.
855 if (I->getOpcode() == Instruction::And) {
856 // If either the LHS or the RHS are Zero, the result is zero.
857 ComputeMaskedBits(I->getOperand(1), DemandedMask,
858 RHSKnownZero, RHSKnownOne, Depth+1);
859 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
860 LHSKnownZero, LHSKnownOne, Depth+1);
861
862 // If all of the demanded bits are known 1 on one side, return the other.
863 // These bits cannot contribute to the result of the 'and' in this
864 // context.
865 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
866 (DemandedMask & ~LHSKnownZero))
867 return I->getOperand(0);
868 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
869 (DemandedMask & ~RHSKnownZero))
870 return I->getOperand(1);
871
872 // If all of the demanded bits in the inputs are known zeros, return zero.
873 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000874 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000875
876 } else if (I->getOpcode() == Instruction::Or) {
877 // We can simplify (X|Y) -> X or Y in the user's context if we know that
878 // only bits from X or Y are demanded.
879
880 // If either the LHS or the RHS are One, the result is One.
881 ComputeMaskedBits(I->getOperand(1), DemandedMask,
882 RHSKnownZero, RHSKnownOne, Depth+1);
883 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
884 LHSKnownZero, LHSKnownOne, Depth+1);
885
886 // If all of the demanded bits are known zero on one side, return the
887 // other. These bits cannot contribute to the result of the 'or' in this
888 // context.
889 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
890 (DemandedMask & ~LHSKnownOne))
891 return I->getOperand(0);
892 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
893 (DemandedMask & ~RHSKnownOne))
894 return I->getOperand(1);
895
896 // If all of the potentially set bits on one side are known to be set on
897 // the other side, just use the 'other' side.
898 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
899 (DemandedMask & (~RHSKnownZero)))
900 return I->getOperand(0);
901 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
902 (DemandedMask & (~LHSKnownZero)))
903 return I->getOperand(1);
904 }
905
Chris Lattner4598c942009-01-31 08:24:16 +0000906 // Compute the KnownZero/KnownOne bits to simplify things downstream.
907 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
908 return 0;
909 }
910
911 // If this is the root being simplified, allow it to have multiple uses,
912 // just set the DemandedMask to all bits so that we can try to simplify the
913 // operands. This allows visitTruncInst (for example) to simplify the
914 // operand of a trunc without duplicating all the logic below.
915 if (Depth == 0 && !V->hasOneUse())
916 DemandedMask = APInt::getAllOnesValue(BitWidth);
917
Reid Spencer8cb68342007-03-12 17:25:59 +0000918 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000919 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000921 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000922 case Instruction::And:
923 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
925 RHSKnownZero, RHSKnownOne, Depth+1) ||
926 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000927 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000928 return I;
929 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
930 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000931
932 // If all of the demanded bits are known 1 on one side, return the other.
933 // These bits cannot contribute to the result of the 'and'.
934 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
935 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000936 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
938 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // If all of the demanded bits in the inputs are known zeros, return zero.
942 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000943 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000944
945 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000946 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000947 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000948
949 // Output known-1 bits are only known if set in both the LHS & RHS.
950 RHSKnownOne &= LHSKnownOne;
951 // Output known-0 are known to be clear if zero in either the LHS | RHS.
952 RHSKnownZero |= LHSKnownZero;
953 break;
954 case Instruction::Or:
955 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
957 RHSKnownZero, RHSKnownOne, Depth+1) ||
958 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000959 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 return I;
961 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
962 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000963
964 // If all of the demanded bits are known zero on one side, return the other.
965 // These bits cannot contribute to the result of the 'or'.
966 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
967 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000969 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
970 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000972
973 // If all of the potentially set bits on one side are known to be set on
974 // the other side, just use the 'other' side.
975 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
976 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000978 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
979 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000983 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000985
986 // Output known-0 bits are only known if clear in both the LHS & RHS.
987 RHSKnownZero &= LHSKnownZero;
988 // Output known-1 are known to be set if set in either the LHS | RHS.
989 RHSKnownOne |= LHSKnownOne;
990 break;
991 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
993 RHSKnownZero, RHSKnownOne, Depth+1) ||
994 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000995 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I;
997 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
998 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000999
1000 // If all of the demanded bits are known zero on one side, return the other.
1001 // These bits cannot contribute to the result of the 'xor'.
1002 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001004 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001006
1007 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1008 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1009 (RHSKnownOne & LHSKnownOne);
1010 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1011 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1012 (RHSKnownOne & LHSKnownZero);
1013
1014 // If all of the demanded bits are known to be zero on one side or the
1015 // other, turn this into an *inclusive* or.
1016 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001017 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1018 Instruction *Or =
1019 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1020 I->getName());
1021 return InsertNewInstBefore(Or, *I);
1022 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001023
1024 // If all of the demanded bits on one side are known, and all of the set
1025 // bits on that side are also known to be set on the other side, turn this
1026 // into an AND, as we know the bits will be cleared.
1027 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1028 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1029 // all known
1030 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001031 Constant *AndC = Constant::getIntegerValue(VTy,
1032 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001033 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001034 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001035 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001036 }
1037 }
1038
1039 // If the RHS is a constant, see if we can simplify it.
1040 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001041 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001043
1044 RHSKnownZero = KnownZeroOut;
1045 RHSKnownOne = KnownOneOut;
1046 break;
1047 }
1048 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1050 RHSKnownZero, RHSKnownOne, Depth+1) ||
1051 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001052 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return I;
1054 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1055 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001056
1057 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001058 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1059 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001061
1062 // Only known if known in both the LHS and RHS.
1063 RHSKnownOne &= LHSKnownOne;
1064 RHSKnownZero &= LHSKnownZero;
1065 break;
1066 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001067 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001068 DemandedMask.zext(truncBf);
1069 RHSKnownZero.zext(truncBf);
1070 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001072 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001074 DemandedMask.trunc(BitWidth);
1075 RHSKnownZero.trunc(BitWidth);
1076 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001077 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001078 break;
1079 }
1080 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001081 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001083
1084 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1085 if (const VectorType *SrcVTy =
1086 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1087 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1088 // Don't touch a bitcast between vectors of different element counts.
1089 return false;
1090 } else
1091 // Don't touch a scalar-to-vector bitcast.
1092 return false;
1093 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1094 // Don't touch a vector-to-scalar bitcast.
1095 return false;
1096
Chris Lattner886ab6c2009-01-31 08:15:18 +00001097 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001098 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return I;
1100 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001101 break;
1102 case Instruction::ZExt: {
1103 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001104 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001105
Zhou Shengd48653a2007-03-29 04:45:55 +00001106 DemandedMask.trunc(SrcBitWidth);
1107 RHSKnownZero.trunc(SrcBitWidth);
1108 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001109 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001110 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 DemandedMask.zext(BitWidth);
1113 RHSKnownZero.zext(BitWidth);
1114 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001116 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001117 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001118 break;
1119 }
1120 case Instruction::SExt: {
1121 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001122 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001123
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001125 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001126
Zhou Sheng01542f32007-03-29 02:26:30 +00001127 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001128 // If any of the sign extended bits are demanded, we know that the sign
1129 // bit is demanded.
1130 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001131 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001132
Zhou Shengd48653a2007-03-29 04:45:55 +00001133 InputDemandedBits.trunc(SrcBitWidth);
1134 RHSKnownZero.trunc(SrcBitWidth);
1135 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001137 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001138 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001139 InputDemandedBits.zext(BitWidth);
1140 RHSKnownZero.zext(BitWidth);
1141 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001143
1144 // If the sign bit of the input is known set or clear, then we know the
1145 // top bits of the result.
1146
1147 // If the input sign bit is known zero, or if the NewBits are not demanded
1148 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001149 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001151 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1152 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001153 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001154 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 }
1156 break;
1157 }
1158 case Instruction::Add: {
1159 // Figure out what the input bits are. If the top bits of the and result
1160 // are not demanded, then the add doesn't demand them from its input
1161 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001163
1164 // If there is a constant on the RHS, there are a variety of xformations
1165 // we can do.
1166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1167 // If null, this should be simplified elsewhere. Some of the xforms here
1168 // won't work if the RHS is zero.
1169 if (RHS->isZero())
1170 break;
1171
1172 // If the top bit of the output is demanded, demand everything from the
1173 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001174 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001175
1176 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001177 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001178 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001179 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
1181 // If the RHS of the add has bits set that can't affect the input, reduce
1182 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001183 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001185
1186 // Avoid excess work.
1187 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1188 break;
1189
1190 // Turn it into OR if input bits are zero.
1191 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1192 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001193 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001194 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001195 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001196 }
1197
1198 // We can say something about the output known-zero and known-one bits,
1199 // depending on potential carries from the input constant and the
1200 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1201 // bits set and the RHS constant is 0x01001, then we know we have a known
1202 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1203
1204 // To compute this, we first compute the potential carry bits. These are
1205 // the bits which may be modified. I'm not aware of a better way to do
1206 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001207 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001208 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001209
1210 // Now that we know which bits have carries, compute the known-1/0 sets.
1211
1212 // Bits are known one if they are known zero in one operand and one in the
1213 // other, and there is no input carry.
1214 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1215 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1216
1217 // Bits are known zero if they are known zero in both operands and there
1218 // is no input carry.
1219 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1220 } else {
1221 // If the high-bits of this ADD are not demanded, then it does not demand
1222 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001223 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 // Right fill the mask of bits for this ADD to demand the most
1225 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1228 LHSKnownZero, LHSKnownOne, Depth+1) ||
1229 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001231 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 }
1233 }
1234 break;
1235 }
1236 case Instruction::Sub:
1237 // If the high-bits of this SUB are not demanded, then it does not demand
1238 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001239 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 // Right fill the mask of bits for this SUB to demand the most
1241 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001242 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001243 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001244 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1245 LHSKnownZero, LHSKnownOne, Depth+1) ||
1246 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001248 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001249 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001250 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1251 // the known zeros and ones.
1252 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 break;
1254 case Instruction::Shl:
1255 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001256 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001257 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001258 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001260 return I;
1261 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 RHSKnownZero <<= ShiftAmt;
1263 RHSKnownOne <<= ShiftAmt;
1264 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001265 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001266 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 }
1268 break;
1269 case Instruction::LShr:
1270 // For a logical shift right
1271 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001272 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001273
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001276 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001277 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001278 return I;
1279 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1281 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001282 if (ShiftAmt) {
1283 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001284 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001285 RHSKnownZero |= HighBits; // high bits known zero.
1286 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 }
1288 break;
1289 case Instruction::AShr:
1290 // If this is an arithmetic shift right and only the low-bit is set, we can
1291 // always convert this into a logical shr, even if the shift amount is
1292 // variable. The low bit of the shift cannot be an input sign bit unless
1293 // the shift amount is >= the size of the datatype, which is undefined.
1294 if (DemandedMask == 1) {
1295 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001298 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001299 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001300
1301 // If the sign bit is the only bit demanded by this ashr, then there is no
1302 // need to do it, the shift doesn't change the high bit.
1303 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001305
1306 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001307 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001308
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001310 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001311 // If any of the "high bits" are demanded, we should set the sign bit as
1312 // demanded.
1313 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1314 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001315 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001317 return I;
1318 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001319 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001320 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1322 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1323
1324 // Handle the sign bits.
1325 APInt SignBit(APInt::getSignBit(BitWidth));
1326 // Adjust to where it is now in the mask.
1327 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1328
1329 // If the input sign bit is known to be zero, or if none of the top bits
1330 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001331 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 (HighBits & ~DemandedMask) == HighBits) {
1333 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001334 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001335 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1338 RHSKnownOne |= HighBits;
1339 }
1340 }
1341 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001342 case Instruction::SRem:
1343 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001344 APInt RA = Rem->getValue().abs();
1345 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001346 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001348
Nick Lewycky8e394322008-11-02 02:41:50 +00001349 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001352 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001354
1355 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1356 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001357
1358 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001359
Chris Lattner886ab6c2009-01-31 08:15:18 +00001360 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001361 }
1362 }
1363 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001364 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001365 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1366 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1368 KnownZero2, KnownOne2, Depth+1) ||
1369 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001370 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001372
Chris Lattner455e9ab2009-01-21 18:09:24 +00001373 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001374 Leaders = std::max(Leaders,
1375 KnownZero2.countLeadingOnes());
1376 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001377 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001378 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001379 case Instruction::Call:
1380 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1381 switch (II->getIntrinsicID()) {
1382 default: break;
1383 case Intrinsic::bswap: {
1384 // If the only bits demanded come from one byte of the bswap result,
1385 // just shift the input byte into position to eliminate the bswap.
1386 unsigned NLZ = DemandedMask.countLeadingZeros();
1387 unsigned NTZ = DemandedMask.countTrailingZeros();
1388
1389 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1390 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1391 // have 14 leading zeros, round to 8.
1392 NLZ &= ~7;
1393 NTZ &= ~7;
1394 // If we need exactly one byte, we can do this transformation.
1395 if (BitWidth-NLZ-NTZ == 8) {
1396 unsigned ResultBit = NTZ;
1397 unsigned InputBit = BitWidth-NTZ-8;
1398
1399 // Replace this with either a left or right shift to get the byte into
1400 // the right place.
1401 Instruction *NewVal;
1402 if (InputBit > ResultBit)
1403 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001404 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001405 else
1406 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001407 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001408 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001409 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001410 }
1411
1412 // TODO: Could compute known zero/one bits based on the input.
1413 break;
1414 }
1415 }
1416 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001417 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001418 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001419 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001420
1421 // If the client is only demanding bits that we know, return the known
1422 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001423 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1424 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 return false;
1426}
1427
Chris Lattner867b99f2006-10-05 06:55:50 +00001428
Mon P Wangaeb06d22008-11-10 04:46:22 +00001429/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001430/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001431/// actually used by the caller. This method analyzes which elements of the
1432/// operand are undef and returns that information in UndefElts.
1433///
1434/// If the information about demanded elements can be used to simplify the
1435/// operation, the operation is simplified, then the resultant value is
1436/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001437Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1438 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001439 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001440 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001441 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001442 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001443
1444 if (isa<UndefValue>(V)) {
1445 // If the entire vector is undefined, just return this info.
1446 UndefElts = EltMask;
1447 return 0;
1448 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1449 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001450 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001452
Chris Lattner867b99f2006-10-05 06:55:50 +00001453 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001454 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1455 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001456 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001457
1458 std::vector<Constant*> Elts;
1459 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001460 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001462 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1464 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001465 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 } else { // Otherwise, defined.
1467 Elts.push_back(CP->getOperand(i));
1468 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001469
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001471 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 return NewCP != CP ? NewCP : 0;
1473 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001474 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001476
1477 // Check if this is identity. If so, return 0 since we are not simplifying
1478 // anything.
1479 if (DemandedElts == ((1ULL << VWidth) -1))
1480 return 0;
1481
Reid Spencer9d6565a2007-02-15 02:26:10 +00001482 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001483 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001484 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001486 for (unsigned i = 0; i != VWidth; ++i) {
1487 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1488 Elts.push_back(Elt);
1489 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001491 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001492 }
1493
Dan Gohman488fbfc2008-09-09 18:11:14 +00001494 // Limit search depth.
1495 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001496 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001497
1498 // If multiple users are using the root value, procede with
1499 // simplification conservatively assuming that all elements
1500 // are needed.
1501 if (!V->hasOneUse()) {
1502 // Quit if we find multiple users of a non-root value though.
1503 // They'll be handled when it's their turn to be visited by
1504 // the main instcombine process.
1505 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001506 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001507 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001508
1509 // Conservatively assume that all elements are needed.
1510 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 }
1512
1513 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001514 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001515
1516 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001517 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 Value *TmpV;
1519 switch (I->getOpcode()) {
1520 default: break;
1521
1522 case Instruction::InsertElement: {
1523 // If this is a variable index, we don't know which element it overwrites.
1524 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001525 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 if (Idx == 0) {
1527 // Note that we can't propagate undef elt info, because we don't know
1528 // which elt is getting updated.
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530 UndefElts2, Depth+1);
1531 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532 break;
1533 }
1534
1535 // If this is inserting an element that isn't demanded, remove this
1536 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001537 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001538 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1539 Worklist.Add(I);
1540 return I->getOperand(0);
1541 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001542
1543 // Otherwise, the element inserted overwrites whatever was there, so the
1544 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001545 APInt DemandedElts2 = DemandedElts;
1546 DemandedElts2.clear(IdxNo);
1547 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001548 UndefElts, Depth+1);
1549 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1550
1551 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001552 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001553 break;
1554 }
1555 case Instruction::ShuffleVector: {
1556 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001557 uint64_t LHSVWidth =
1558 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001559 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001561 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001562 unsigned MaskVal = Shuffle->getMaskValue(i);
1563 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001564 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001566 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001567 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568 else
Evan Cheng388df622009-02-03 10:05:09 +00001569 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 }
1571 }
1572 }
1573
Nate Begeman7b254672009-02-11 22:36:25 +00001574 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001576 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1578
Nate Begeman7b254672009-02-11 22:36:25 +00001579 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1581 UndefElts3, Depth+1);
1582 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1583
1584 bool NewUndefElts = false;
1585 for (unsigned i = 0; i < VWidth; i++) {
1586 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001587 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001588 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001589 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001590 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001591 NewUndefElts = true;
1592 UndefElts.set(i);
1593 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001594 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001595 if (UndefElts3[MaskVal - LHSVWidth]) {
1596 NewUndefElts = true;
1597 UndefElts.set(i);
1598 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001599 }
1600 }
1601
1602 if (NewUndefElts) {
1603 // Add additional discovered undefs.
1604 std::vector<Constant*> Elts;
1605 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001606 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001607 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001608 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001609 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001610 Shuffle->getMaskValue(i)));
1611 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001612 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001613 MadeChange = true;
1614 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001615 break;
1616 }
Chris Lattner69878332007-04-14 22:29:23 +00001617 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001618 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001619 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1620 if (!VTy) break;
1621 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001622 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001623 unsigned Ratio;
1624
1625 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001626 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001627 // elements as are demanded of us.
1628 Ratio = 1;
1629 InputDemandedElts = DemandedElts;
1630 } else if (VWidth > InVWidth) {
1631 // Untested so far.
1632 break;
1633
1634 // If there are more elements in the result than there are in the source,
1635 // then an input element is live if any of the corresponding output
1636 // elements are live.
1637 Ratio = VWidth/InVWidth;
1638 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001639 if (DemandedElts[OutIdx])
1640 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001641 }
1642 } else {
1643 // Untested so far.
1644 break;
1645
1646 // If there are more elements in the source than there are in the result,
1647 // then an input element is live if the corresponding output element is
1648 // live.
1649 Ratio = InVWidth/VWidth;
1650 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001651 if (DemandedElts[InIdx/Ratio])
1652 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001653 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001654
Chris Lattner69878332007-04-14 22:29:23 +00001655 // div/rem demand all inputs, because they don't want divide by zero.
1656 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1657 UndefElts2, Depth+1);
1658 if (TmpV) {
1659 I->setOperand(0, TmpV);
1660 MadeChange = true;
1661 }
1662
1663 UndefElts = UndefElts2;
1664 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001665 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001666 // If there are more elements in the result than there are in the source,
1667 // then an output element is undef if the corresponding input element is
1668 // undef.
1669 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001670 if (UndefElts2[OutIdx/Ratio])
1671 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001672 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001673 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001674 // If there are more elements in the source than there are in the result,
1675 // then a result element is undef if all of the corresponding input
1676 // elements are undef.
1677 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1678 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001679 if (!UndefElts2[InIdx]) // Not undef?
1680 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001681 }
1682 break;
1683 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001684 case Instruction::And:
1685 case Instruction::Or:
1686 case Instruction::Xor:
1687 case Instruction::Add:
1688 case Instruction::Sub:
1689 case Instruction::Mul:
1690 // div/rem demand all inputs, because they don't want divide by zero.
1691 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1692 UndefElts, Depth+1);
1693 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1694 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1695 UndefElts2, Depth+1);
1696 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1697
1698 // Output elements are undefined if both are undefined. Consider things
1699 // like undef&0. The result is known zero, not undef.
1700 UndefElts &= UndefElts2;
1701 break;
1702
1703 case Instruction::Call: {
1704 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1705 if (!II) break;
1706 switch (II->getIntrinsicID()) {
1707 default: break;
1708
1709 // Binary vector operations that work column-wise. A dest element is a
1710 // function of the corresponding input elements from the two inputs.
1711 case Intrinsic::x86_sse_sub_ss:
1712 case Intrinsic::x86_sse_mul_ss:
1713 case Intrinsic::x86_sse_min_ss:
1714 case Intrinsic::x86_sse_max_ss:
1715 case Intrinsic::x86_sse2_sub_sd:
1716 case Intrinsic::x86_sse2_mul_sd:
1717 case Intrinsic::x86_sse2_min_sd:
1718 case Intrinsic::x86_sse2_max_sd:
1719 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1720 UndefElts, Depth+1);
1721 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1722 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1723 UndefElts2, Depth+1);
1724 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1725
1726 // If only the low elt is demanded and this is a scalarizable intrinsic,
1727 // scalarize it now.
1728 if (DemandedElts == 1) {
1729 switch (II->getIntrinsicID()) {
1730 default: break;
1731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse_mul_ss:
1733 case Intrinsic::x86_sse2_sub_sd:
1734 case Intrinsic::x86_sse2_mul_sd:
1735 // TODO: Lower MIN/MAX/ABS/etc
1736 Value *LHS = II->getOperand(1);
1737 Value *RHS = II->getOperand(2);
1738 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001739 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001740 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001741 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001742 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001743
1744 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001745 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001746 case Intrinsic::x86_sse_sub_ss:
1747 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001748 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001749 II->getName()), *II);
1750 break;
1751 case Intrinsic::x86_sse_mul_ss:
1752 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001753 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001754 II->getName()), *II);
1755 break;
1756 }
1757
1758 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001759 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001760 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001761 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001762 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001763 return New;
1764 }
1765 }
1766
1767 // Output elements are undefined if both are undefined. Consider things
1768 // like undef&0. The result is known zero, not undef.
1769 UndefElts &= UndefElts2;
1770 break;
1771 }
1772 break;
1773 }
1774 }
1775 return MadeChange ? I : 0;
1776}
1777
Dan Gohman45b4e482008-05-19 22:14:15 +00001778
Chris Lattner564a7272003-08-13 19:01:45 +00001779/// AssociativeOpt - Perform an optimization on an associative operator. This
1780/// function is designed to check a chain of associative operators for a
1781/// potential to apply a certain optimization. Since the optimization may be
1782/// applicable if the expression was reassociated, this checks the chain, then
1783/// reassociates the expression as necessary to expose the optimization
1784/// opportunity. This makes use of a special Functor, which must define
1785/// 'shouldApply' and 'apply' methods.
1786///
1787template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001788static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001789 unsigned Opcode = Root.getOpcode();
1790 Value *LHS = Root.getOperand(0);
1791
1792 // Quick check, see if the immediate LHS matches...
1793 if (F.shouldApply(LHS))
1794 return F.apply(Root);
1795
1796 // Otherwise, if the LHS is not of the same opcode as the root, return.
1797 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001798 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001799 // Should we apply this transform to the RHS?
1800 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1801
1802 // If not to the RHS, check to see if we should apply to the LHS...
1803 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1804 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1805 ShouldApply = true;
1806 }
1807
1808 // If the functor wants to apply the optimization to the RHS of LHSI,
1809 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1810 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001811 // Now all of the instructions are in the current basic block, go ahead
1812 // and perform the reassociation.
1813 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1814
1815 // First move the selected RHS to the LHS of the root...
1816 Root.setOperand(0, LHSI->getOperand(1));
1817
1818 // Make what used to be the LHS of the root be the user of the root...
1819 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001820 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001821 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001822 return 0;
1823 }
Chris Lattner65725312004-04-16 18:08:07 +00001824 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001825 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001826 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001827 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001828 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001829
1830 // Now propagate the ExtraOperand down the chain of instructions until we
1831 // get to LHSI.
1832 while (TmpLHSI != LHSI) {
1833 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001834 // Move the instruction to immediately before the chain we are
1835 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001836 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001837 ARI = NextLHSI;
1838
Chris Lattner564a7272003-08-13 19:01:45 +00001839 Value *NextOp = NextLHSI->getOperand(1);
1840 NextLHSI->setOperand(1, ExtraOperand);
1841 TmpLHSI = NextLHSI;
1842 ExtraOperand = NextOp;
1843 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001844
Chris Lattner564a7272003-08-13 19:01:45 +00001845 // Now that the instructions are reassociated, have the functor perform
1846 // the transformation...
1847 return F.apply(Root);
1848 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001849
Chris Lattner564a7272003-08-13 19:01:45 +00001850 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1851 }
1852 return 0;
1853}
1854
Dan Gohman844731a2008-05-13 00:00:25 +00001855namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001856
Nick Lewycky02d639f2008-05-23 04:34:58 +00001857// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001858struct AddRHS {
1859 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001860 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001861 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1862 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001863 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001864 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001865 }
1866};
1867
1868// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1869// iff C1&C2 == 0
1870struct AddMaskingAnd {
1871 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001872 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001873 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001874 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001875 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001876 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001877 }
1878 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001879 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001880 }
1881};
1882
Dan Gohman844731a2008-05-13 00:00:25 +00001883}
1884
Chris Lattner6e7ba452005-01-01 16:22:27 +00001885static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001886 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001887 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001888 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001889
Chris Lattner2eefe512004-04-09 19:05:30 +00001890 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001891 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1892 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001893
Chris Lattner2eefe512004-04-09 19:05:30 +00001894 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1895 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001896 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1897 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001898 }
1899
1900 Value *Op0 = SO, *Op1 = ConstOperand;
1901 if (!ConstIsRHS)
1902 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001903
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001905 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1906 SO->getName()+".op");
1907 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1908 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1909 SO->getName()+".cmp");
1910 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1911 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1912 SO->getName()+".cmp");
1913 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001914}
1915
1916// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1917// constant as the other operand, try to fold the binary operator into the
1918// select arguments. This also works for Cast instructions, which obviously do
1919// not have a second operand.
1920static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1921 InstCombiner *IC) {
1922 // Don't modify shared select instructions
1923 if (!SI->hasOneUse()) return 0;
1924 Value *TV = SI->getOperand(1);
1925 Value *FV = SI->getOperand(2);
1926
1927 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001928 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001929 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001930
Chris Lattner6e7ba452005-01-01 16:22:27 +00001931 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1932 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1933
Gabor Greif051a9502008-04-06 20:25:17 +00001934 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1935 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001936 }
1937 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001938}
1939
Chris Lattner4e998b22004-09-29 05:07:12 +00001940
1941/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1942/// node as operand #0, see if we can fold the instruction into the PHI (which
1943/// is only possible if all operands to the PHI are constants).
1944Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1945 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001946 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001947 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001948
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001949 // Check to see if all of the operands of the PHI are constants. If there is
1950 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001951 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001952 BasicBlock *NonConstBB = 0;
1953 for (unsigned i = 0; i != NumPHIValues; ++i)
1954 if (!isa<Constant>(PN->getIncomingValue(i))) {
1955 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001956 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001957 NonConstBB = PN->getIncomingBlock(i);
1958
1959 // If the incoming non-constant value is in I's block, we have an infinite
1960 // loop.
1961 if (NonConstBB == I.getParent())
1962 return 0;
1963 }
1964
1965 // If there is exactly one non-constant value, we can insert a copy of the
1966 // operation in that block. However, if this is a critical edge, we would be
1967 // inserting the computation one some other paths (e.g. inside a loop). Only
1968 // do this if the pred block is unconditionally branching into the phi block.
1969 if (NonConstBB) {
1970 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1971 if (!BI || !BI->isUnconditional()) return 0;
1972 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001973
1974 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001975 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001976 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001977 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001978 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001979
1980 // Next, add all of the operands to the PHI.
1981 if (I.getNumOperands() == 2) {
1982 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001983 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001984 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001985 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001986 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001987 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001988 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001989 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001990 } else {
1991 assert(PN->getIncomingBlock(i) == NonConstBB);
1992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001993 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001994 PN->getIncomingValue(i), C, "phitmp",
1995 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001996 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001997 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001998 CI->getPredicate(),
1999 PN->getIncomingValue(i), C, "phitmp",
2000 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002001 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002002 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002003
Chris Lattner7a1e9242009-08-30 06:13:40 +00002004 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002005 }
2006 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002007 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002008 } else {
2009 CastInst *CI = cast<CastInst>(&I);
2010 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002011 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002012 Value *InV;
2013 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002014 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015 } else {
2016 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002017 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002018 I.getType(), "phitmp",
2019 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002020 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002021 }
2022 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002023 }
2024 }
2025 return ReplaceInstUsesWith(I, NewPN);
2026}
2027
Chris Lattner2454a2e2008-01-29 06:52:45 +00002028
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002029/// WillNotOverflowSignedAdd - Return true if we can prove that:
2030/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2031/// This basically requires proving that the add in the original type would not
2032/// overflow to change the sign bit or have a carry out.
2033bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2034 // There are different heuristics we can use for this. Here are some simple
2035 // ones.
2036
2037 // Add has the property that adding any two 2's complement numbers can only
2038 // have one carry bit which can change a sign. As such, if LHS and RHS each
2039 // have at least two sign bits, we know that the addition of the two values will
2040 // sign extend fine.
2041 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2042 return true;
2043
2044
2045 // If one of the operands only has one non-zero bit, and if the other operand
2046 // has a known-zero bit in a more significant place than it (not including the
2047 // sign bit) the ripple may go up to and fill the zero, but won't change the
2048 // sign. For example, (X & ~4) + 1.
2049
2050 // TODO: Implement.
2051
2052 return false;
2053}
2054
Chris Lattner2454a2e2008-01-29 06:52:45 +00002055
Chris Lattner7e708292002-06-25 16:13:24 +00002056Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002057 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002058 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002059
Chris Lattner66331a42004-04-10 22:01:55 +00002060 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002061 // X + undef -> undef
2062 if (isa<UndefValue>(RHS))
2063 return ReplaceInstUsesWith(I, RHS);
2064
Chris Lattner66331a42004-04-10 22:01:55 +00002065 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002066 if (RHSC->isNullValue())
2067 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002068
Chris Lattner66331a42004-04-10 22:01:55 +00002069 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002070 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002071 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002072 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002073 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002074 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002075
2076 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2077 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002078 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002079 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002080
Eli Friedman709b33d2009-07-13 22:27:52 +00002081 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002082 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002083 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002084 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002085 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002086
2087 if (isa<PHINode>(LHS))
2088 if (Instruction *NV = FoldOpIntoPhi(I))
2089 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002090
Chris Lattner4f637d42006-01-06 17:59:59 +00002091 ConstantInt *XorRHS = 0;
2092 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002093 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002094 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002095 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002096 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002097
Zhou Sheng4351c642007-04-02 08:20:41 +00002098 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002099 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2100 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002101 do {
2102 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002103 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2104 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002105 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2106 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002107 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002108 if (!MaskedValueIsZero(XorLHS,
2109 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002110 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002111 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002112 }
2113 }
2114 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002115 C0080Val = APIntOps::lshr(C0080Val, Size);
2116 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2117 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002118
Reid Spencer35c38852007-03-28 01:36:16 +00002119 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002120 // with funny bit widths then this switch statement should be removed. It
2121 // is just here to get the size of the "middle" type back up to something
2122 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002123 const Type *MiddleType = 0;
2124 switch (Size) {
2125 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002126 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2127 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2128 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002129 }
2130 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002131 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002132 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002133 }
2134 }
Chris Lattner66331a42004-04-10 22:01:55 +00002135 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002136
Owen Anderson1d0be152009-08-13 21:58:54 +00002137 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002138 return BinaryOperator::CreateXor(LHS, RHS);
2139
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002140 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002141 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002142 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002143 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002144
2145 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2146 if (RHSI->getOpcode() == Instruction::Sub)
2147 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2148 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2149 }
2150 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2151 if (LHSI->getOpcode() == Instruction::Sub)
2152 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2153 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2154 }
Robert Bocchino71698282004-07-27 21:02:21 +00002155 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002156
Chris Lattner5c4afb92002-05-08 22:46:53 +00002157 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002158 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002159 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002160 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002161 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002162 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002163 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002164 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002165 }
2166
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002167 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002168 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002169
2170 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002171 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002172 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002173 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002174
Misha Brukmanfd939082005-04-21 23:48:37 +00002175
Chris Lattner50af16a2004-11-13 19:50:12 +00002176 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002177 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002178 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002179 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002180
2181 // X*C1 + X*C2 --> X * (C1+C2)
2182 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002183 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002184 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002185 }
2186
2187 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002188 if (dyn_castFoldableMul(RHS, C2) == LHS)
2189 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002190
Chris Lattnere617c9e2007-01-05 02:17:46 +00002191 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002192 if (dyn_castNotVal(LHS) == RHS ||
2193 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002194 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002195
Chris Lattnerad3448c2003-02-18 19:57:07 +00002196
Chris Lattner564a7272003-08-13 19:01:45 +00002197 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002198 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2199 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002200 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002201
2202 // A+B --> A|B iff A and B have no bits set in common.
2203 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2204 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2205 APInt LHSKnownOne(IT->getBitWidth(), 0);
2206 APInt LHSKnownZero(IT->getBitWidth(), 0);
2207 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2208 if (LHSKnownZero != 0) {
2209 APInt RHSKnownOne(IT->getBitWidth(), 0);
2210 APInt RHSKnownZero(IT->getBitWidth(), 0);
2211 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2212
2213 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002214 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002215 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002216 }
2217 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002218
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002219 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002220 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002221 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002222 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2223 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002224 if (W != Y) {
2225 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002226 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002227 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002228 std::swap(W, X);
2229 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002230 std::swap(Y, Z);
2231 std::swap(W, X);
2232 }
2233 }
2234
2235 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002236 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002237 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002238 }
2239 }
2240 }
2241
Chris Lattner6b032052003-10-02 15:11:26 +00002242 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002243 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002244 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002245 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002246
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002247 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002248 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002249 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002250 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002251 if (Anded == CRHS) {
2252 // See if all bits from the first bit set in the Add RHS up are included
2253 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002254 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002255
2256 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002257 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258
2259 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002260 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002261
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2263 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002264 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002265 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002266 }
2267 }
2268 }
2269
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002270 // Try to fold constant add into select arguments.
2271 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002272 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002273 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002274 }
2275
Chris Lattner42790482007-12-20 01:56:58 +00002276 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002277 {
2278 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002279 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002280 if (!SI) {
2281 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002282 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002283 }
Chris Lattner42790482007-12-20 01:56:58 +00002284 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002285 Value *TV = SI->getTrueValue();
2286 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002287 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002288
2289 // Can we fold the add into the argument of the select?
2290 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002291 if (match(FV, m_Zero()) &&
2292 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002293 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002294 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002295 if (match(TV, m_Zero()) &&
2296 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002297 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002298 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002299 }
2300 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002301
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002302 // Check for (add (sext x), y), see if we can merge this into an
2303 // integer add followed by a sext.
2304 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2305 // (add (sext x), cst) --> (sext (add x, cst'))
2306 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2307 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002308 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002309 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002310 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002311 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2312 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002313 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2314 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002315 return new SExtInst(NewAdd, I.getType());
2316 }
2317 }
2318
2319 // (add (sext x), (sext y)) --> (sext (add int x, y))
2320 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2321 // Only do this if x/y have the same type, if at last one of them has a
2322 // single use (so we don't increase the number of sexts), and if the
2323 // integer add will not overflow.
2324 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2325 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2326 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2327 RHSConv->getOperand(0))) {
2328 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002329 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2330 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002331 return new SExtInst(NewAdd, I.getType());
2332 }
2333 }
2334 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002335
2336 return Changed ? &I : 0;
2337}
2338
2339Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2340 bool Changed = SimplifyCommutative(I);
2341 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2342
2343 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2344 // X + 0 --> X
2345 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002346 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002347 (I.getType())->getValueAPF()))
2348 return ReplaceInstUsesWith(I, LHS);
2349 }
2350
2351 if (isa<PHINode>(LHS))
2352 if (Instruction *NV = FoldOpIntoPhi(I))
2353 return NV;
2354 }
2355
2356 // -A + B --> B - A
2357 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002358 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002359 return BinaryOperator::CreateFSub(RHS, LHSV);
2360
2361 // A + -B --> A - B
2362 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002363 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002364 return BinaryOperator::CreateFSub(LHS, V);
2365
2366 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2367 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2368 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2369 return ReplaceInstUsesWith(I, LHS);
2370
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002371 // Check for (add double (sitofp x), y), see if we can merge this into an
2372 // integer add followed by a promotion.
2373 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2374 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2375 // ... if the constant fits in the integer value. This is useful for things
2376 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2377 // requires a constant pool load, and generally allows the add to be better
2378 // instcombined.
2379 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2380 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002381 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002382 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002383 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002384 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2385 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002386 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2387 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002388 return new SIToFPInst(NewAdd, I.getType());
2389 }
2390 }
2391
2392 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2393 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2394 // Only do this if x/y have the same type, if at last one of them has a
2395 // single use (so we don't increase the number of int->fp conversions),
2396 // and if the integer add will not overflow.
2397 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2398 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2399 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2400 RHSConv->getOperand(0))) {
2401 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002402 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2403 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002404 return new SIToFPInst(NewAdd, I.getType());
2405 }
2406 }
2407 }
2408
Chris Lattner7e708292002-06-25 16:13:24 +00002409 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002410}
2411
Chris Lattner7e708292002-06-25 16:13:24 +00002412Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002414
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002415 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002416 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002417
Chris Lattner233f7dc2002-08-12 21:17:25 +00002418 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002419 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002420 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002421
Chris Lattnere87597f2004-10-16 18:11:37 +00002422 if (isa<UndefValue>(Op0))
2423 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2424 if (isa<UndefValue>(Op1))
2425 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2426
Chris Lattnerd65460f2003-11-05 01:06:05 +00002427 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2428 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002429 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002430 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002431
Chris Lattnerd65460f2003-11-05 01:06:05 +00002432 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002433 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002434 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002435 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002436
Chris Lattner76b7a062007-01-15 07:02:54 +00002437 // -(X >>u 31) -> (X >>s 31)
2438 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002439 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002440 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002441 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002442 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002443 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002444 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002445 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002446 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002448 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002449 }
2450 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002451 }
2452 else if (SI->getOpcode() == Instruction::AShr) {
2453 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2454 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002455 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002456 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002457 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002459 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002460 }
2461 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002462 }
2463 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002464 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002465
2466 // Try to fold constant sub into select arguments.
2467 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002468 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002469 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002470
2471 // C - zext(bool) -> bool ? C - 1 : C
2472 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002473 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002474 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002475 }
2476
Owen Anderson1d0be152009-08-13 21:58:54 +00002477 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002478 return BinaryOperator::CreateXor(Op0, Op1);
2479
Chris Lattner43d84d62005-04-07 16:15:25 +00002480 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002481 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002482 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002483 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002484 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002485 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002486 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002487 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002488 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2489 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2490 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002491 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002492 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002493 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002494 }
2495
Chris Lattnerfd059242003-10-15 16:48:29 +00002496 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002497 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2498 // is not used by anyone else...
2499 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002500 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002501 // Swap the two operands of the subexpr...
2502 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2503 Op1I->setOperand(0, IIOp1);
2504 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002505
Chris Lattnera2881962003-02-18 19:28:33 +00002506 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002507 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002508 }
2509
2510 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2511 //
2512 if (Op1I->getOpcode() == Instruction::And &&
2513 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2514 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2515
Chris Lattner74381062009-08-30 07:44:24 +00002516 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002517 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002518 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002519
Reid Spencerac5209e2006-10-16 23:08:08 +00002520 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002521 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002522 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002523 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002524 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002525 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002526 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002527
Chris Lattnerad3448c2003-02-18 19:57:07 +00002528 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002529 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002530 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002531 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002532 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002533 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002535 }
Chris Lattner40371712002-05-09 01:29:19 +00002536 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002537 }
Chris Lattnera2881962003-02-18 19:28:33 +00002538
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002539 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2540 if (Op0I->getOpcode() == Instruction::Add) {
2541 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2542 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2543 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2544 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2545 } else if (Op0I->getOpcode() == Instruction::Sub) {
2546 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002547 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002548 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002549 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002550 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002551
Chris Lattner50af16a2004-11-13 19:50:12 +00002552 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002553 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002554 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002555 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002556
Chris Lattner50af16a2004-11-13 19:50:12 +00002557 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002558 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002559 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002560 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002561 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002562}
2563
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002564Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2565 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2566
2567 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002568 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002569 return BinaryOperator::CreateFAdd(Op0, V);
2570
2571 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2572 if (Op1I->getOpcode() == Instruction::FAdd) {
2573 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002574 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002575 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002576 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002577 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002578 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002579 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580 }
2581
2582 return 0;
2583}
2584
Chris Lattnera0141b92007-07-15 20:42:37 +00002585/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2586/// comparison only checks the sign bit. If it only checks the sign bit, set
2587/// TrueIfSigned if the result of the comparison is true when the input value is
2588/// signed.
2589static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2590 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002591 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002592 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2593 TrueIfSigned = true;
2594 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002595 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2596 TrueIfSigned = true;
2597 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002598 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2599 TrueIfSigned = false;
2600 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002601 case ICmpInst::ICMP_UGT:
2602 // True if LHS u> RHS and RHS == high-bit-mask - 1
2603 TrueIfSigned = true;
2604 return RHS->getValue() ==
2605 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2606 case ICmpInst::ICMP_UGE:
2607 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2608 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002609 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002610 default:
2611 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002612 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002613}
2614
Chris Lattner7e708292002-06-25 16:13:24 +00002615Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002616 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002617 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002618
Eli Friedman1694e092009-07-18 09:12:15 +00002619 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002620 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002621
Chris Lattner233f7dc2002-08-12 21:17:25 +00002622 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002623 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2624 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002625
2626 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002627 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002628 if (SI->getOpcode() == Instruction::Shl)
2629 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002630 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002631 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002632
Zhou Sheng843f07672007-04-19 05:39:12 +00002633 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002634 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2635 if (CI->equalsInt(1)) // X * 1 == X
2636 return ReplaceInstUsesWith(I, Op0);
2637 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002638 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002639
Zhou Sheng97b52c22007-03-29 01:57:21 +00002640 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002641 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002642 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002643 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002644 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002645 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002646 if (Op1->isNullValue())
2647 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002648
2649 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2650 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002651 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002652
2653 // As above, vector X*splat(1.0) -> X in all defined cases.
2654 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002655 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2656 if (CI->equalsInt(1))
2657 return ReplaceInstUsesWith(I, Op0);
2658 }
2659 }
Chris Lattnera2881962003-02-18 19:28:33 +00002660 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002661
2662 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2663 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002664 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002665 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002666 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2667 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002669
2670 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002671
2672 // Try to fold constant mul into select arguments.
2673 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002674 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002675 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002676
2677 if (isa<PHINode>(Op0))
2678 if (Instruction *NV = FoldOpIntoPhi(I))
2679 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002680 }
2681
Dan Gohman186a6362009-08-12 16:04:34 +00002682 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2683 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002685
Nick Lewycky0c730792008-11-21 07:33:58 +00002686 // (X / Y) * Y = X - (X % Y)
2687 // (X / Y) * -Y = (X % Y) - X
2688 {
2689 Value *Op1 = I.getOperand(1);
2690 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2691 if (!BO ||
2692 (BO->getOpcode() != Instruction::UDiv &&
2693 BO->getOpcode() != Instruction::SDiv)) {
2694 Op1 = Op0;
2695 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2696 }
Dan Gohman186a6362009-08-12 16:04:34 +00002697 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002698 if (BO && BO->hasOneUse() &&
2699 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2700 (BO->getOpcode() == Instruction::UDiv ||
2701 BO->getOpcode() == Instruction::SDiv)) {
2702 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2703
Dan Gohmanfa94b942009-08-12 16:33:09 +00002704 // If the division is exact, X % Y is zero.
2705 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2706 if (SDiv->isExact()) {
2707 if (Op1BO == Op1)
2708 return ReplaceInstUsesWith(I, Op0BO);
2709 else
2710 return BinaryOperator::CreateNeg(Op0BO);
2711 }
2712
Chris Lattner74381062009-08-30 07:44:24 +00002713 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002714 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002715 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002716 else
Chris Lattner74381062009-08-30 07:44:24 +00002717 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002718 Rem->takeName(BO);
2719
2720 if (Op1BO == Op1)
2721 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002722 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002723 }
2724 }
2725
Owen Anderson1d0be152009-08-13 21:58:54 +00002726 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002727 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2728
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002729 // If one of the operands of the multiply is a cast from a boolean value, then
2730 // we know the bool is either zero or one, so this is a 'masking' multiply.
2731 // See if we can simplify things based on how the boolean was originally
2732 // formed.
2733 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002734 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002735 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002736 BoolCast = CI;
2737 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002738 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002739 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002740 BoolCast = CI;
2741 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002742 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002743 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2744 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002745 bool TIS = false;
2746
Reid Spencere4d87aa2006-12-23 06:05:41 +00002747 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002748 // multiply into a shift/and combination.
2749 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002750 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2751 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002752 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002753 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002754 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002755 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2756 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002757
2758 // If the multiply type is not the same as the source type, sign extend
2759 // or truncate to the multiply type.
Chris Lattner2345d1d2009-08-30 20:01:10 +00002760 if (I.getType() != V->getType())
2761 V = Builder->CreateIntCast(V, I.getType(), true);
Misha Brukmanfd939082005-04-21 23:48:37 +00002762
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002763 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002764 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002765 }
2766 }
2767 }
2768
Chris Lattner7e708292002-06-25 16:13:24 +00002769 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002770}
2771
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002772Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2773 bool Changed = SimplifyCommutative(I);
2774 Value *Op0 = I.getOperand(0);
2775
2776 // Simplify mul instructions with a constant RHS...
2777 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2778 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2779 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2780 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2781 if (Op1F->isExactlyValue(1.0))
2782 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2783 } else if (isa<VectorType>(Op1->getType())) {
2784 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2785 // As above, vector X*splat(1.0) -> X in all defined cases.
2786 if (Constant *Splat = Op1V->getSplatValue()) {
2787 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2788 if (F->isExactlyValue(1.0))
2789 return ReplaceInstUsesWith(I, Op0);
2790 }
2791 }
2792 }
2793
2794 // Try to fold constant mul into select arguments.
2795 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2796 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2797 return R;
2798
2799 if (isa<PHINode>(Op0))
2800 if (Instruction *NV = FoldOpIntoPhi(I))
2801 return NV;
2802 }
2803
Dan Gohman186a6362009-08-12 16:04:34 +00002804 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2805 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002806 return BinaryOperator::CreateFMul(Op0v, Op1v);
2807
2808 return Changed ? &I : 0;
2809}
2810
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002811/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2812/// instruction.
2813bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2814 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2815
2816 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2817 int NonNullOperand = -1;
2818 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2819 if (ST->isNullValue())
2820 NonNullOperand = 2;
2821 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2822 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2823 if (ST->isNullValue())
2824 NonNullOperand = 1;
2825
2826 if (NonNullOperand == -1)
2827 return false;
2828
2829 Value *SelectCond = SI->getOperand(0);
2830
2831 // Change the div/rem to use 'Y' instead of the select.
2832 I.setOperand(1, SI->getOperand(NonNullOperand));
2833
2834 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2835 // problem. However, the select, or the condition of the select may have
2836 // multiple uses. Based on our knowledge that the operand must be non-zero,
2837 // propagate the known value for the select into other uses of it, and
2838 // propagate a known value of the condition into its other users.
2839
2840 // If the select and condition only have a single use, don't bother with this,
2841 // early exit.
2842 if (SI->use_empty() && SelectCond->hasOneUse())
2843 return true;
2844
2845 // Scan the current block backward, looking for other uses of SI.
2846 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2847
2848 while (BBI != BBFront) {
2849 --BBI;
2850 // If we found a call to a function, we can't assume it will return, so
2851 // information from below it cannot be propagated above it.
2852 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2853 break;
2854
2855 // Replace uses of the select or its condition with the known values.
2856 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2857 I != E; ++I) {
2858 if (*I == SI) {
2859 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002860 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002861 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002862 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2863 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002864 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002865 }
2866 }
2867
2868 // If we past the instruction, quit looking for it.
2869 if (&*BBI == SI)
2870 SI = 0;
2871 if (&*BBI == SelectCond)
2872 SelectCond = 0;
2873
2874 // If we ran out of things to eliminate, break out of the loop.
2875 if (SelectCond == 0 && SI == 0)
2876 break;
2877
2878 }
2879 return true;
2880}
2881
2882
Reid Spencer1628cec2006-10-26 06:15:43 +00002883/// This function implements the transforms on div instructions that work
2884/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2885/// used by the visitors to those instructions.
2886/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002887Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002889
Chris Lattner50b2ca42008-02-19 06:12:18 +00002890 // undef / X -> 0 for integer.
2891 // undef / X -> undef for FP (the undef could be a snan).
2892 if (isa<UndefValue>(Op0)) {
2893 if (Op0->getType()->isFPOrFPVector())
2894 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002895 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002896 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002897
2898 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002899 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002900 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002901
Reid Spencer1628cec2006-10-26 06:15:43 +00002902 return 0;
2903}
Misha Brukmanfd939082005-04-21 23:48:37 +00002904
Reid Spencer1628cec2006-10-26 06:15:43 +00002905/// This function implements the transforms common to both integer division
2906/// instructions (udiv and sdiv). It is called by the visitors to those integer
2907/// division instructions.
2908/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002909Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002910 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2911
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002912 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002913 if (Op0 == Op1) {
2914 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002915 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002916 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002917 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002918 }
2919
Owen Andersoneed707b2009-07-24 23:12:02 +00002920 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002921 return ReplaceInstUsesWith(I, CI);
2922 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002923
Reid Spencer1628cec2006-10-26 06:15:43 +00002924 if (Instruction *Common = commonDivTransforms(I))
2925 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002926
2927 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2928 // This does not apply for fdiv.
2929 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2930 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002931
2932 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2933 // div X, 1 == X
2934 if (RHS->equalsInt(1))
2935 return ReplaceInstUsesWith(I, Op0);
2936
2937 // (X / C1) / C2 -> X / (C1*C2)
2938 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2939 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2940 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002941 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002942 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002943 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002944 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002945 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002946 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002947 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002948
Reid Spencerbca0e382007-03-23 20:05:17 +00002949 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002950 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2951 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2952 return R;
2953 if (isa<PHINode>(Op0))
2954 if (Instruction *NV = FoldOpIntoPhi(I))
2955 return NV;
2956 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002957 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002958
Chris Lattnera2881962003-02-18 19:28:33 +00002959 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002960 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002961 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002962 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002963
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002964 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002965 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002966 return ReplaceInstUsesWith(I, Op0);
2967
Nick Lewycky895f0852008-11-27 20:21:08 +00002968 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2969 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2970 // div X, 1 == X
2971 if (X->isOne())
2972 return ReplaceInstUsesWith(I, Op0);
2973 }
2974
Reid Spencer1628cec2006-10-26 06:15:43 +00002975 return 0;
2976}
2977
2978Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2979 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2980
2981 // Handle the integer div common cases
2982 if (Instruction *Common = commonIDivTransforms(I))
2983 return Common;
2984
Reid Spencer1628cec2006-10-26 06:15:43 +00002985 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002986 // X udiv C^2 -> X >> C
2987 // Check to see if this is an unsigned division with an exact power of 2,
2988 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002989 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002990 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002991 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002992
2993 // X udiv C, where C >= signbit
2994 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00002995 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00002996 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00002997 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002998 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002999 }
3000
3001 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003002 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 if (RHSI->getOpcode() == Instruction::Shl &&
3004 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003005 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003006 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003007 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003008 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003009 if (uint32_t C2 = C1.logBase2())
3010 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003011 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003012 }
3013 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003014 }
3015
Reid Spencer1628cec2006-10-26 06:15:43 +00003016 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3017 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003018 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003019 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003020 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003021 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003022 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003023 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003024 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003025 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003026 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003027 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003028
3029 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003030 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003031 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003032
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003033 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003034 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003035 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003036 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003037 return 0;
3038}
3039
Reid Spencer1628cec2006-10-26 06:15:43 +00003040Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3041 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3042
3043 // Handle the integer div common cases
3044 if (Instruction *Common = commonIDivTransforms(I))
3045 return Common;
3046
3047 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3048 // sdiv X, -1 == -X
3049 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003050 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003051
Dan Gohmanfa94b942009-08-12 16:33:09 +00003052 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003053 if (cast<SDivOperator>(&I)->isExact() &&
3054 RHS->getValue().isNonNegative() &&
3055 RHS->getValue().isPowerOf2()) {
3056 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3057 RHS->getValue().exactLogBase2());
3058 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3059 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003060
3061 // -X/C --> X/-C provided the negation doesn't overflow.
3062 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3063 if (isa<Constant>(Sub->getOperand(0)) &&
3064 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003065 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003066 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3067 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003068 }
3069
3070 // If the sign bits of both operands are zero (i.e. we can prove they are
3071 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003072 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003073 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003074 if (MaskedValueIsZero(Op0, Mask)) {
3075 if (MaskedValueIsZero(Op1, Mask)) {
3076 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3077 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3078 }
3079 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003080 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003081 ShiftedInt->getValue().isPowerOf2()) {
3082 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3083 // Safe because the only negative value (1 << Y) can take on is
3084 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3085 // the sign bit set.
3086 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3087 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003088 }
Eli Friedman8be17392009-07-18 09:53:21 +00003089 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003090
3091 return 0;
3092}
3093
3094Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3095 return commonDivTransforms(I);
3096}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003097
Reid Spencer0a783f72006-11-02 01:53:59 +00003098/// This function implements the transforms on rem instructions that work
3099/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3100/// is used by the visitors to those instructions.
3101/// @brief Transforms common to all three rem instructions
3102Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003103 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003104
Chris Lattner50b2ca42008-02-19 06:12:18 +00003105 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3106 if (I.getType()->isFPOrFPVector())
3107 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003108 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003109 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003110 if (isa<UndefValue>(Op1))
3111 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003112
3113 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003114 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3115 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003116
Reid Spencer0a783f72006-11-02 01:53:59 +00003117 return 0;
3118}
3119
3120/// This function implements the transforms common to both integer remainder
3121/// instructions (urem and srem). It is called by the visitors to those integer
3122/// remainder instructions.
3123/// @brief Common integer remainder transforms
3124Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3126
3127 if (Instruction *common = commonRemTransforms(I))
3128 return common;
3129
Dale Johannesened6af242009-01-21 00:35:19 +00003130 // 0 % X == 0 for integer, we don't need to preserve faults!
3131 if (Constant *LHS = dyn_cast<Constant>(Op0))
3132 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003134
Chris Lattner857e8cd2004-12-12 21:48:58 +00003135 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003136 // X % 0 == undef, we don't need to preserve faults!
3137 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003138 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003139
Chris Lattnera2881962003-02-18 19:28:33 +00003140 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003142
Chris Lattner97943922006-02-28 05:49:21 +00003143 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3144 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3145 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3146 return R;
3147 } else if (isa<PHINode>(Op0I)) {
3148 if (Instruction *NV = FoldOpIntoPhi(I))
3149 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003150 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003151
3152 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003153 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003154 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003155 }
Chris Lattnera2881962003-02-18 19:28:33 +00003156 }
3157
Reid Spencer0a783f72006-11-02 01:53:59 +00003158 return 0;
3159}
3160
3161Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3163
3164 if (Instruction *common = commonIRemTransforms(I))
3165 return common;
3166
3167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3168 // X urem C^2 -> X and C
3169 // Check to see if this is an unsigned remainder with an exact power of 2,
3170 // if so, convert to a bitwise and.
3171 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003172 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003173 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003174 }
3175
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003176 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003177 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3178 if (RHSI->getOpcode() == Instruction::Shl &&
3179 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003180 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003181 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003182 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003183 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003184 }
3185 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003186 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003187
Reid Spencer0a783f72006-11-02 01:53:59 +00003188 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189 // where C1&C2 are powers of two.
3190 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003194 if ((STO->getValue().isPowerOf2()) &&
3195 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003196 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3197 SI->getName()+".t");
3198 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3199 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003200 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003201 }
3202 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003203 }
3204
Chris Lattner3f5b8772002-05-06 16:14:14 +00003205 return 0;
3206}
3207
Reid Spencer0a783f72006-11-02 01:53:59 +00003208Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
Dan Gohmancff55092007-11-05 23:16:33 +00003211 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003212 if (Instruction *Common = commonIRemTransforms(I))
3213 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003214
Dan Gohman186a6362009-08-12 16:04:34 +00003215 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003216 if (!isa<Constant>(RHSNeg) ||
3217 (isa<ConstantInt>(RHSNeg) &&
3218 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003220 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003221 I.setOperand(1, RHSNeg);
3222 return &I;
3223 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003224
Dan Gohmancff55092007-11-05 23:16:33 +00003225 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003226 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003227 if (I.getType()->isInteger()) {
3228 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3229 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3230 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003231 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003232 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 }
3234
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003235 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003236 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3237 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003238
Nick Lewycky9dce8732008-12-20 16:48:00 +00003239 bool hasNegative = false;
3240 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3242 if (RHS->getValue().isNegative())
3243 hasNegative = true;
3244
3245 if (hasNegative) {
3246 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003247 for (unsigned i = 0; i != VWidth; ++i) {
3248 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3249 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003250 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003251 else
3252 Elts[i] = RHS;
3253 }
3254 }
3255
Owen Andersonaf7ec972009-07-28 21:19:26 +00003256 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003257 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003258 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003259 I.setOperand(1, NewRHSV);
3260 return &I;
3261 }
3262 }
3263 }
3264
Reid Spencer0a783f72006-11-02 01:53:59 +00003265 return 0;
3266}
3267
3268Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003269 return commonRemTransforms(I);
3270}
3271
Chris Lattner457dd822004-06-09 07:59:58 +00003272// isOneBitSet - Return true if there is exactly one bit set in the specified
3273// constant.
3274static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003275 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003276}
3277
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003278// isHighOnes - Return true if the constant is of the form 1+0+.
3279// This is the same as lowones(~X).
3280static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003281 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003282}
3283
Reid Spencere4d87aa2006-12-23 06:05:41 +00003284/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003285/// are carefully arranged to allow folding of expressions such as:
3286///
3287/// (A < B) | (A > B) --> (A != B)
3288///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003289/// Note that this is only valid if the first and second predicates have the
3290/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003291///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003292/// Three bits are used to represent the condition, as follows:
3293/// 0 A > B
3294/// 1 A == B
3295/// 2 A < B
3296///
3297/// <=> Value Definition
3298/// 000 0 Always false
3299/// 001 1 A > B
3300/// 010 2 A == B
3301/// 011 3 A >= B
3302/// 100 4 A < B
3303/// 101 5 A != B
3304/// 110 6 A <= B
3305/// 111 7 Always true
3306///
3307static unsigned getICmpCode(const ICmpInst *ICI) {
3308 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003309 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003310 case ICmpInst::ICMP_UGT: return 1; // 001
3311 case ICmpInst::ICMP_SGT: return 1; // 001
3312 case ICmpInst::ICMP_EQ: return 2; // 010
3313 case ICmpInst::ICMP_UGE: return 3; // 011
3314 case ICmpInst::ICMP_SGE: return 3; // 011
3315 case ICmpInst::ICMP_ULT: return 4; // 100
3316 case ICmpInst::ICMP_SLT: return 4; // 100
3317 case ICmpInst::ICMP_NE: return 5; // 101
3318 case ICmpInst::ICMP_ULE: return 6; // 110
3319 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003320 // True -> 7
3321 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003322 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003323 return 0;
3324 }
3325}
3326
Evan Cheng8db90722008-10-14 17:15:11 +00003327/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3328/// predicate into a three bit mask. It also returns whether it is an ordered
3329/// predicate by reference.
3330static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3331 isOrdered = false;
3332 switch (CC) {
3333 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3334 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003335 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3336 case FCmpInst::FCMP_UGT: return 1; // 001
3337 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3338 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003339 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3340 case FCmpInst::FCMP_UGE: return 3; // 011
3341 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3342 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003343 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3344 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003345 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3346 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003347 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003348 default:
3349 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003350 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003351 return 0;
3352 }
3353}
3354
Reid Spencere4d87aa2006-12-23 06:05:41 +00003355/// getICmpValue - This is the complement of getICmpCode, which turns an
3356/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003357/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003358/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003359static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003360 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003361 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003362 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003363 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003364 case 1:
3365 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003366 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003368 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3369 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370 case 3:
3371 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003372 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003373 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003374 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003375 case 4:
3376 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003377 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003379 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3380 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381 case 6:
3382 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003383 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003385 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003386 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003387 }
3388}
3389
Evan Cheng8db90722008-10-14 17:15:11 +00003390/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3391/// opcode and two operands into either a FCmp instruction. isordered is passed
3392/// in to determine which kind of predicate to use in the new fcmp instruction.
3393static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003394 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003395 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003396 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003397 case 0:
3398 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003399 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003400 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003401 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003402 case 1:
3403 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003404 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003405 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003406 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003407 case 2:
3408 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003409 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003410 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003411 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003412 case 3:
3413 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003414 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003415 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003416 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003417 case 4:
3418 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003419 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003420 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003421 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003422 case 5:
3423 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003424 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003425 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003426 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003427 case 6:
3428 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003432 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 }
3434}
3435
Chris Lattnerb9553d62008-11-16 04:55:20 +00003436/// PredicatesFoldable - Return true if both predicates match sign or if at
3437/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003438static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3439 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003440 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3441 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003442}
3443
3444namespace {
3445// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3446struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003447 InstCombiner &IC;
3448 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449 ICmpInst::Predicate pred;
3450 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3451 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3452 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003453 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003454 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3455 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003456 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3457 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003458 return false;
3459 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460 Instruction *apply(Instruction &Log) const {
3461 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3462 if (ICI->getOperand(0) != LHS) {
3463 assert(ICI->getOperand(1) == LHS);
3464 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003465 }
3466
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003467 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003468 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003469 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003470 unsigned Code;
3471 switch (Log.getOpcode()) {
3472 case Instruction::And: Code = LHSCode & RHSCode; break;
3473 case Instruction::Or: Code = LHSCode | RHSCode; break;
3474 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003475 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003476 }
3477
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003478 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3479 ICmpInst::isSignedPredicate(ICI->getPredicate());
3480
Owen Andersond672ecb2009-07-03 00:17:18 +00003481 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003482 if (Instruction *I = dyn_cast<Instruction>(RV))
3483 return I;
3484 // Otherwise, it's a constant boolean value...
3485 return IC.ReplaceInstUsesWith(Log, RV);
3486 }
3487};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003488} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003489
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003490// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3491// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003492// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003493Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003494 ConstantInt *OpRHS,
3495 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003496 BinaryOperator &TheAnd) {
3497 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003498 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003499 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003500 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003501
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003502 switch (Op->getOpcode()) {
3503 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003504 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003505 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003506 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003507 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003508 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003509 }
3510 break;
3511 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003512 if (Together == AndRHS) // (X | C) & C --> C
3513 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003514
Chris Lattner6e7ba452005-01-01 16:22:27 +00003515 if (Op->hasOneUse() && Together != OpRHS) {
3516 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003517 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003518 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003519 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520 }
3521 break;
3522 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003523 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003524 // Adding a one to a single bit bit-field should be turned into an XOR
3525 // of the bit. First thing to check is to see if this AND is with a
3526 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003527 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003528
3529 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003530 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003531 // Ok, at this point, we know that we are masking the result of the
3532 // ADD down to exactly one bit. If the constant we are adding has
3533 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003534 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003535
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003536 // Check to see if any bits below the one bit set in AndRHSV are set.
3537 if ((AddRHS & (AndRHSV-1)) == 0) {
3538 // If not, the only thing that can effect the output of the AND is
3539 // the bit specified by AndRHSV. If that bit is set, the effect of
3540 // the XOR is to toggle the bit. If it is clear, then the ADD has
3541 // no effect.
3542 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3543 TheAnd.setOperand(0, X);
3544 return &TheAnd;
3545 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003547 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003548 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 }
3551 }
3552 }
3553 }
3554 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003555
3556 case Instruction::Shl: {
3557 // We know that the AND will not produce any of the bits shifted in, so if
3558 // the anded constant includes them, clear them now!
3559 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003560 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003561 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003562 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003563 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003564
Zhou Sheng290bec52007-03-29 08:15:12 +00003565 if (CI->getValue() == ShlMask) {
3566 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003567 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3568 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003569 TheAnd.setOperand(1, CI);
3570 return &TheAnd;
3571 }
3572 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003573 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003574 case Instruction::LShr:
3575 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003576 // We know that the AND will not produce any of the bits shifted in, so if
3577 // the anded constant includes them, clear them now! This only applies to
3578 // unsigned shifts, because a signed shr may bring in set bits!
3579 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003580 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003581 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003582 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003583 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003584
Zhou Sheng290bec52007-03-29 08:15:12 +00003585 if (CI->getValue() == ShrMask) {
3586 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003587 return ReplaceInstUsesWith(TheAnd, Op);
3588 } else if (CI != AndRHS) {
3589 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3590 return &TheAnd;
3591 }
3592 break;
3593 }
3594 case Instruction::AShr:
3595 // Signed shr.
3596 // See if this is shifting in some sign extension, then masking it out
3597 // with an and.
3598 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003600 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003602 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003603 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003604 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003605 // Make the argument unsigned.
3606 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003607 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003608 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003609 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003610 }
3611 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003612 }
3613 return 0;
3614}
3615
Chris Lattner8b170942002-08-09 23:47:40 +00003616
Chris Lattnera96879a2004-09-29 17:40:11 +00003617/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3618/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003619/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3620/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003621/// insert new instructions.
3622Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003623 bool isSigned, bool Inside,
3624 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003625 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003626 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003627 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003628
Chris Lattnera96879a2004-09-29 17:40:11 +00003629 if (Inside) {
3630 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003631 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003632
Reid Spencere4d87aa2006-12-23 06:05:41 +00003633 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003634 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003635 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003637 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003638 }
3639
3640 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003641 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003642 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003643 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003644 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 }
3646
3647 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003648 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003649
Reid Spencere4e40032007-03-21 23:19:50 +00003650 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003651 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003652 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 ICmpInst::Predicate pred = (isSigned ?
3654 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003655 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003657
Reid Spencere4e40032007-03-21 23:19:50 +00003658 // Emit V-Lo >u Hi-1-Lo
3659 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003660 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003661 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003662 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003663 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003664}
3665
Chris Lattner7203e152005-09-18 07:22:02 +00003666// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3667// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3668// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3669// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003670static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003671 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003672 uint32_t BitWidth = Val->getType()->getBitWidth();
3673 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003674
3675 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003676 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003677 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003678 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003679 return true;
3680}
3681
Chris Lattner7203e152005-09-18 07:22:02 +00003682/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3683/// where isSub determines whether the operator is a sub. If we can fold one of
3684/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003685///
3686/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3687/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3688/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3689///
3690/// return (A +/- B).
3691///
3692Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003693 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003694 Instruction &I) {
3695 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3696 if (!LHSI || LHSI->getNumOperands() != 2 ||
3697 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3698
3699 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3700
3701 switch (LHSI->getOpcode()) {
3702 default: return 0;
3703 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003704 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003705 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003706 if ((Mask->getValue().countLeadingZeros() +
3707 Mask->getValue().countPopulation()) ==
3708 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003709 break;
3710
3711 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3712 // part, we don't need any explicit masks to take them out of A. If that
3713 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003714 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003715 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003716 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003717 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003718 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003719 break;
3720 }
3721 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003722 return 0;
3723 case Instruction::Or:
3724 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003725 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003726 if ((Mask->getValue().countLeadingZeros() +
3727 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003728 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003729 break;
3730 return 0;
3731 }
3732
Chris Lattnerc8e77562005-09-18 04:24:45 +00003733 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003734 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3735 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003736}
3737
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003738/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3739Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3740 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003741 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003742 ConstantInt *LHSCst, *RHSCst;
3743 ICmpInst::Predicate LHSCC, RHSCC;
3744
Chris Lattnerea065fb2008-11-16 05:10:52 +00003745 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003746 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003747 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003748 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003749 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003750 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003751
3752 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3753 // where C is a power of 2
3754 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3755 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003756 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003757 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003758 }
3759
3760 // From here on, we only handle:
3761 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3762 if (Val != Val2) return 0;
3763
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003764 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3765 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3766 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3767 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3768 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3769 return 0;
3770
3771 // We can't fold (ugt x, C) & (sgt x, C2).
3772 if (!PredicatesFoldable(LHSCC, RHSCC))
3773 return 0;
3774
3775 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003776 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003777 if (ICmpInst::isSignedPredicate(LHSCC) ||
3778 (ICmpInst::isEquality(LHSCC) &&
3779 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003780 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003781 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003782 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3783
3784 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003785 std::swap(LHS, RHS);
3786 std::swap(LHSCst, RHSCst);
3787 std::swap(LHSCC, RHSCC);
3788 }
3789
3790 // At this point, we know we have have two icmp instructions
3791 // comparing a value against two constants and and'ing the result
3792 // together. Because of the above check, we know that we only have
3793 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3794 // (from the FoldICmpLogical check above), that the two constants
3795 // are not equal and that the larger constant is on the RHS
3796 assert(LHSCst != RHSCst && "Compares not folded above?");
3797
3798 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003799 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003800 case ICmpInst::ICMP_EQ:
3801 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003802 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3804 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3805 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003806 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3808 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3809 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3810 return ReplaceInstUsesWith(I, LHS);
3811 }
3812 case ICmpInst::ICMP_NE:
3813 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003814 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003815 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003816 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003817 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003818 break; // (X != 13 & X u< 15) -> no change
3819 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003820 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003821 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003822 break; // (X != 13 & X s< 15) -> no change
3823 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3824 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3825 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3826 return ReplaceInstUsesWith(I, RHS);
3827 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003828 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003829 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003830 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003831 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003832 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003833 }
3834 break; // (X != 13 & X != 15) -> no change
3835 }
3836 break;
3837 case ICmpInst::ICMP_ULT:
3838 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003839 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3841 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003842 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003843 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3844 break;
3845 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3846 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3847 return ReplaceInstUsesWith(I, LHS);
3848 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3849 break;
3850 }
3851 break;
3852 case ICmpInst::ICMP_SLT:
3853 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003854 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003855 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3856 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003857 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3859 break;
3860 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3861 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3862 return ReplaceInstUsesWith(I, LHS);
3863 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3864 break;
3865 }
3866 break;
3867 case ICmpInst::ICMP_UGT:
3868 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003869 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003870 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3871 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3872 return ReplaceInstUsesWith(I, RHS);
3873 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3874 break;
3875 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003876 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003877 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003879 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003880 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003881 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003882 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3883 break;
3884 }
3885 break;
3886 case ICmpInst::ICMP_SGT:
3887 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003888 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003889 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3890 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3891 return ReplaceInstUsesWith(I, RHS);
3892 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3893 break;
3894 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003895 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003896 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003898 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003899 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003900 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3902 break;
3903 }
3904 break;
3905 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003906
3907 return 0;
3908}
3909
Chris Lattner42d1be02009-07-23 05:14:02 +00003910Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3911 FCmpInst *RHS) {
3912
3913 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3914 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3915 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3916 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3917 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3918 // If either of the constants are nans, then the whole thing returns
3919 // false.
3920 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003921 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003922 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003923 LHS->getOperand(0), RHS->getOperand(0));
3924 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003925
3926 // Handle vector zeros. This occurs because the canonical form of
3927 // "fcmp ord x,x" is "fcmp ord x, 0".
3928 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3929 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003930 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003931 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003932 return 0;
3933 }
3934
3935 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3936 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3937 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3938
3939
3940 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3941 // Swap RHS operands to match LHS.
3942 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3943 std::swap(Op1LHS, Op1RHS);
3944 }
3945
3946 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3947 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3948 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003949 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003950
3951 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003952 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003953 if (Op0CC == FCmpInst::FCMP_TRUE)
3954 return ReplaceInstUsesWith(I, RHS);
3955 if (Op1CC == FCmpInst::FCMP_TRUE)
3956 return ReplaceInstUsesWith(I, LHS);
3957
3958 bool Op0Ordered;
3959 bool Op1Ordered;
3960 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3961 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3962 if (Op1Pred == 0) {
3963 std::swap(LHS, RHS);
3964 std::swap(Op0Pred, Op1Pred);
3965 std::swap(Op0Ordered, Op1Ordered);
3966 }
3967 if (Op0Pred == 0) {
3968 // uno && ueq -> uno && (uno || eq) -> ueq
3969 // ord && olt -> ord && (ord && lt) -> olt
3970 if (Op0Ordered == Op1Ordered)
3971 return ReplaceInstUsesWith(I, RHS);
3972
3973 // uno && oeq -> uno && (ord && eq) -> false
3974 // uno && ord -> false
3975 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003976 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003977 // ord && ueq -> ord && (uno || eq) -> oeq
3978 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3979 Op0LHS, Op0RHS, Context));
3980 }
3981 }
3982
3983 return 0;
3984}
3985
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003986
Chris Lattner7e708292002-06-25 16:13:24 +00003987Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003988 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003990
Chris Lattnere87597f2004-10-16 18:11:37 +00003991 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003992 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003993
Chris Lattner6e7ba452005-01-01 16:22:27 +00003994 // and X, X = X
3995 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003996 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003997
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003998 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003999 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004000 if (SimplifyDemandedInstructionBits(I))
4001 return &I;
4002 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004003 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004004 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004005 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004006 } else if (isa<ConstantAggregateZero>(Op1)) {
4007 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004008 }
4009 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004010
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004011 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004012 const APInt& AndRHSMask = AndRHS->getValue();
4013 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004014
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004015 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004016 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004017 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004018 Value *Op0LHS = Op0I->getOperand(0);
4019 Value *Op0RHS = Op0I->getOperand(1);
4020 switch (Op0I->getOpcode()) {
4021 case Instruction::Xor:
4022 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004023 // If the mask is only needed on one incoming arm, push it up.
4024 if (Op0I->hasOneUse()) {
4025 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4026 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004027 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4028 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004029 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004030 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004031 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004032 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004033 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4034 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004035 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4036 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004037 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004038 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4039 }
4040 }
4041
Chris Lattner6e7ba452005-01-01 16:22:27 +00004042 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004043 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004044 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4045 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4046 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4047 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004048 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004049 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004050 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004051 break;
4052
4053 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004054 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4055 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4056 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4057 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004058 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004059
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004060 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4061 // has 1's for all bits that the subtraction with A might affect.
4062 if (Op0I->hasOneUse()) {
4063 uint32_t BitWidth = AndRHSMask.getBitWidth();
4064 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4065 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4066
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004067 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004068 if (!(A && A->isZero()) && // avoid infinite recursion.
4069 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004070 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004071 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4072 }
4073 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004074 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004075
4076 case Instruction::Shl:
4077 case Instruction::LShr:
4078 // (1 << x) & 1 --> zext(x == 0)
4079 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004080 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004081 Value *NewICmp =
4082 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004083 return new ZExtInst(NewICmp, I.getType());
4084 }
4085 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004086 }
4087
Chris Lattner58403262003-07-23 19:25:52 +00004088 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004089 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004090 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004091 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004092 // If this is an integer truncation or change from signed-to-unsigned, and
4093 // if the source is an and/or with immediate, transform it. This
4094 // frequently occurs for bitfield accesses.
4095 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004096 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004097 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004098 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004099 if (CastOp->getOpcode() == Instruction::And) {
4100 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004101 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4102 // This will fold the two constants together, which may allow
4103 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004104 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004105 CastOp->getOperand(0), I.getType(),
4106 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004107 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004108 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004109 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004110 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004111 } else if (CastOp->getOpcode() == Instruction::Or) {
4112 // Change: and (cast (or X, C1) to T), C2
4113 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004114 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004115 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004116 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004117 return ReplaceInstUsesWith(I, AndRHS);
4118 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004119 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004120 }
Chris Lattner06782f82003-07-23 19:36:21 +00004121 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004122
4123 // Try to fold constant and into select arguments.
4124 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004125 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004126 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004127 if (isa<PHINode>(Op0))
4128 if (Instruction *NV = FoldOpIntoPhi(I))
4129 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004130 }
4131
Dan Gohman186a6362009-08-12 16:04:34 +00004132 Value *Op0NotVal = dyn_castNotVal(Op0);
4133 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004134
Chris Lattner5b62aa72004-06-18 06:07:51 +00004135 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004136 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004137
Misha Brukmancb6267b2004-07-30 12:50:08 +00004138 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004139 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004140 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4141 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004142 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004143 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004144
4145 {
Chris Lattner003b6202007-06-15 05:58:24 +00004146 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004147 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004148 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4149 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004150
4151 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004152 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004153 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004154 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004155 }
4156 }
4157
Dan Gohman4ae51262009-08-12 16:23:25 +00004158 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004159 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4160 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004161
4162 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004163 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004164 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004165 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004166 }
4167 }
Chris Lattner64daab52006-04-01 08:03:55 +00004168
4169 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004170 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004171 if (A == Op1) { // (A^B)&A -> A&(A^B)
4172 I.swapOperands(); // Simplify below
4173 std::swap(Op0, Op1);
4174 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4175 cast<BinaryOperator>(Op0)->swapOperands();
4176 I.swapOperands(); // Simplify below
4177 std::swap(Op0, Op1);
4178 }
4179 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004180
Chris Lattner64daab52006-04-01 08:03:55 +00004181 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004182 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004183 if (B == Op0) { // B&(A^B) -> B&(B^A)
4184 cast<BinaryOperator>(Op1)->swapOperands();
4185 std::swap(A, B);
4186 }
Chris Lattner74381062009-08-30 07:44:24 +00004187 if (A == Op0) // A&(A^B) -> A & ~B
4188 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004189 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004190
4191 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004192 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4193 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004194 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004195 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4196 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004197 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004198 }
4199
Reid Spencere4d87aa2006-12-23 06:05:41 +00004200 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4201 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004202 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004203 return R;
4204
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004205 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4206 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4207 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004208 }
4209
Chris Lattner6fc205f2006-05-05 06:39:07 +00004210 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004211 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4212 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4213 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4214 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004215 if (SrcTy == Op1C->getOperand(0)->getType() &&
4216 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004217 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4219 I.getType(), TD) &&
4220 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4221 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004222 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4223 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004224 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004225 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004226 }
Chris Lattnere511b742006-11-14 07:46:50 +00004227
4228 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004229 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4230 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4231 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004232 SI0->getOperand(1) == SI1->getOperand(1) &&
4233 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004234 Value *NewOp =
4235 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4236 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004237 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004238 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004239 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004240 }
4241
Evan Cheng8db90722008-10-14 17:15:11 +00004242 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004243 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004244 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4245 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4246 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004247 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004248
Chris Lattner7e708292002-06-25 16:13:24 +00004249 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004250}
4251
Chris Lattner8c34cd22008-10-05 02:13:19 +00004252/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4253/// capable of providing pieces of a bswap. The subexpression provides pieces
4254/// of a bswap if it is proven that each of the non-zero bytes in the output of
4255/// the expression came from the corresponding "byte swapped" byte in some other
4256/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4257/// we know that the expression deposits the low byte of %X into the high byte
4258/// of the bswap result and that all other bytes are zero. This expression is
4259/// accepted, the high byte of ByteValues is set to X to indicate a correct
4260/// match.
4261///
4262/// This function returns true if the match was unsuccessful and false if so.
4263/// On entry to the function the "OverallLeftShift" is a signed integer value
4264/// indicating the number of bytes that the subexpression is later shifted. For
4265/// example, if the expression is later right shifted by 16 bits, the
4266/// OverallLeftShift value would be -2 on entry. This is used to specify which
4267/// byte of ByteValues is actually being set.
4268///
4269/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4270/// byte is masked to zero by a user. For example, in (X & 255), X will be
4271/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4272/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4273/// always in the local (OverallLeftShift) coordinate space.
4274///
4275static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4276 SmallVector<Value*, 8> &ByteValues) {
4277 if (Instruction *I = dyn_cast<Instruction>(V)) {
4278 // If this is an or instruction, it may be an inner node of the bswap.
4279 if (I->getOpcode() == Instruction::Or) {
4280 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4281 ByteValues) ||
4282 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4283 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004284 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004285
4286 // If this is a logical shift by a constant multiple of 8, recurse with
4287 // OverallLeftShift and ByteMask adjusted.
4288 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4289 unsigned ShAmt =
4290 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4291 // Ensure the shift amount is defined and of a byte value.
4292 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4293 return true;
4294
4295 unsigned ByteShift = ShAmt >> 3;
4296 if (I->getOpcode() == Instruction::Shl) {
4297 // X << 2 -> collect(X, +2)
4298 OverallLeftShift += ByteShift;
4299 ByteMask >>= ByteShift;
4300 } else {
4301 // X >>u 2 -> collect(X, -2)
4302 OverallLeftShift -= ByteShift;
4303 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004304 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004305 }
4306
4307 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4308 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4309
4310 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4311 ByteValues);
4312 }
4313
4314 // If this is a logical 'and' with a mask that clears bytes, clear the
4315 // corresponding bytes in ByteMask.
4316 if (I->getOpcode() == Instruction::And &&
4317 isa<ConstantInt>(I->getOperand(1))) {
4318 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4319 unsigned NumBytes = ByteValues.size();
4320 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4321 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4322
4323 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4324 // If this byte is masked out by a later operation, we don't care what
4325 // the and mask is.
4326 if ((ByteMask & (1 << i)) == 0)
4327 continue;
4328
4329 // If the AndMask is all zeros for this byte, clear the bit.
4330 APInt MaskB = AndMask & Byte;
4331 if (MaskB == 0) {
4332 ByteMask &= ~(1U << i);
4333 continue;
4334 }
4335
4336 // If the AndMask is not all ones for this byte, it's not a bytezap.
4337 if (MaskB != Byte)
4338 return true;
4339
4340 // Otherwise, this byte is kept.
4341 }
4342
4343 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4344 ByteValues);
4345 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004346 }
4347
Chris Lattner8c34cd22008-10-05 02:13:19 +00004348 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4349 // the input value to the bswap. Some observations: 1) if more than one byte
4350 // is demanded from this input, then it could not be successfully assembled
4351 // into a byteswap. At least one of the two bytes would not be aligned with
4352 // their ultimate destination.
4353 if (!isPowerOf2_32(ByteMask)) return true;
4354 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004355
Chris Lattner8c34cd22008-10-05 02:13:19 +00004356 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4357 // is demanded, it needs to go into byte 0 of the result. This means that the
4358 // byte needs to be shifted until it lands in the right byte bucket. The
4359 // shift amount depends on the position: if the byte is coming from the high
4360 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4361 // low part, it must be shifted left.
4362 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4363 if (InputByteNo < ByteValues.size()/2) {
4364 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4365 return true;
4366 } else {
4367 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4368 return true;
4369 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004370
4371 // If the destination byte value is already defined, the values are or'd
4372 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004373 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004374 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004375 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004376 return false;
4377}
4378
4379/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4380/// If so, insert the new bswap intrinsic and return it.
4381Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004382 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004383 if (!ITy || ITy->getBitWidth() % 16 ||
4384 // ByteMask only allows up to 32-byte values.
4385 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004386 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387
4388 /// ByteValues - For each byte of the result, we keep track of which value
4389 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004390 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004391 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004392
4393 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004394 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4395 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004396 return 0;
4397
4398 // Check to see if all of the bytes come from the same value.
4399 Value *V = ByteValues[0];
4400 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4401
4402 // Check to make sure that all of the bytes come from the same value.
4403 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4404 if (ByteValues[i] != V)
4405 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004406 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004407 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004408 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004409 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004410}
4411
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004412/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4413/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4414/// we can simplify this expression to "cond ? C : D or B".
4415static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004416 Value *C, Value *D,
4417 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004418 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004419 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004420 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004421 return 0;
4422
Chris Lattnera6a474d2008-11-16 04:26:55 +00004423 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004424 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004425 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004426 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004427 return SelectInst::Create(Cond, C, B);
4428 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004429 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004430 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004431 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004432 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004433 return 0;
4434}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004435
Chris Lattner69d4ced2008-11-16 05:20:07 +00004436/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4437Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4438 ICmpInst *LHS, ICmpInst *RHS) {
4439 Value *Val, *Val2;
4440 ConstantInt *LHSCst, *RHSCst;
4441 ICmpInst::Predicate LHSCC, RHSCC;
4442
4443 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004444 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004445 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004446 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004447 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004448 return 0;
4449
4450 // From here on, we only handle:
4451 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4452 if (Val != Val2) return 0;
4453
4454 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4455 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4456 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4457 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4458 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4459 return 0;
4460
4461 // We can't fold (ugt x, C) | (sgt x, C2).
4462 if (!PredicatesFoldable(LHSCC, RHSCC))
4463 return 0;
4464
4465 // Ensure that the larger constant is on the RHS.
4466 bool ShouldSwap;
4467 if (ICmpInst::isSignedPredicate(LHSCC) ||
4468 (ICmpInst::isEquality(LHSCC) &&
4469 ICmpInst::isSignedPredicate(RHSCC)))
4470 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4471 else
4472 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4473
4474 if (ShouldSwap) {
4475 std::swap(LHS, RHS);
4476 std::swap(LHSCst, RHSCst);
4477 std::swap(LHSCC, RHSCC);
4478 }
4479
4480 // At this point, we know we have have two icmp instructions
4481 // comparing a value against two constants and or'ing the result
4482 // together. Because of the above check, we know that we only have
4483 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4484 // FoldICmpLogical check above), that the two constants are not
4485 // equal.
4486 assert(LHSCst != RHSCst && "Compares not folded above?");
4487
4488 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004489 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004490 case ICmpInst::ICMP_EQ:
4491 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004492 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004493 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004494 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004495 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004496 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004497 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004498 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004499 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004500 }
4501 break; // (X == 13 | X == 15) -> no change
4502 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4503 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4504 break;
4505 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4506 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4507 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4508 return ReplaceInstUsesWith(I, RHS);
4509 }
4510 break;
4511 case ICmpInst::ICMP_NE:
4512 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004513 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004514 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4515 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4516 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4517 return ReplaceInstUsesWith(I, LHS);
4518 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4519 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4520 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004521 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004522 }
4523 break;
4524 case ICmpInst::ICMP_ULT:
4525 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004526 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004527 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4528 break;
4529 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4530 // If RHSCst is [us]MAXINT, it is always false. Not handling
4531 // this can cause overflow.
4532 if (RHSCst->isMaxValue(false))
4533 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004534 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004535 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004536 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4537 break;
4538 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4539 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4540 return ReplaceInstUsesWith(I, RHS);
4541 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4542 break;
4543 }
4544 break;
4545 case ICmpInst::ICMP_SLT:
4546 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004547 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004548 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4549 break;
4550 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4551 // If RHSCst is [us]MAXINT, it is always false. Not handling
4552 // this can cause overflow.
4553 if (RHSCst->isMaxValue(true))
4554 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004555 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004556 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004557 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4558 break;
4559 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4560 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4561 return ReplaceInstUsesWith(I, RHS);
4562 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4563 break;
4564 }
4565 break;
4566 case ICmpInst::ICMP_UGT:
4567 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004568 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004569 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4570 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4571 return ReplaceInstUsesWith(I, LHS);
4572 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4573 break;
4574 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4575 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004576 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004577 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4578 break;
4579 }
4580 break;
4581 case ICmpInst::ICMP_SGT:
4582 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004583 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004584 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4585 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4586 return ReplaceInstUsesWith(I, LHS);
4587 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4588 break;
4589 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4590 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004591 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4593 break;
4594 }
4595 break;
4596 }
4597 return 0;
4598}
4599
Chris Lattner5414cc52009-07-23 05:46:22 +00004600Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4601 FCmpInst *RHS) {
4602 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4603 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4604 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4605 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4606 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4607 // If either of the constants are nans, then the whole thing returns
4608 // true.
4609 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004610 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004611
4612 // Otherwise, no need to compare the two constants, compare the
4613 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004614 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004615 LHS->getOperand(0), RHS->getOperand(0));
4616 }
4617
4618 // Handle vector zeros. This occurs because the canonical form of
4619 // "fcmp uno x,x" is "fcmp uno x, 0".
4620 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4621 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004622 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004623 LHS->getOperand(0), RHS->getOperand(0));
4624
4625 return 0;
4626 }
4627
4628 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4629 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4630 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4631
4632 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4633 // Swap RHS operands to match LHS.
4634 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4635 std::swap(Op1LHS, Op1RHS);
4636 }
4637 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4638 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4639 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004640 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004641 Op0LHS, Op0RHS);
4642 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004643 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004644 if (Op0CC == FCmpInst::FCMP_FALSE)
4645 return ReplaceInstUsesWith(I, RHS);
4646 if (Op1CC == FCmpInst::FCMP_FALSE)
4647 return ReplaceInstUsesWith(I, LHS);
4648 bool Op0Ordered;
4649 bool Op1Ordered;
4650 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4651 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4652 if (Op0Ordered == Op1Ordered) {
4653 // If both are ordered or unordered, return a new fcmp with
4654 // or'ed predicates.
4655 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4656 Op0LHS, Op0RHS, Context);
4657 if (Instruction *I = dyn_cast<Instruction>(RV))
4658 return I;
4659 // Otherwise, it's a constant boolean value...
4660 return ReplaceInstUsesWith(I, RV);
4661 }
4662 }
4663 return 0;
4664}
4665
Bill Wendlinga698a472008-12-01 08:23:25 +00004666/// FoldOrWithConstants - This helper function folds:
4667///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004668/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004669///
4670/// into:
4671///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004672/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004673///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004674/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004675Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004676 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004677 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4678 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004679
Bill Wendling286a0542008-12-02 06:24:20 +00004680 Value *V1 = 0;
4681 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004682 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004683
Bill Wendling29976b92008-12-02 06:18:11 +00004684 APInt Xor = CI1->getValue() ^ CI2->getValue();
4685 if (!Xor.isAllOnesValue()) return 0;
4686
Bill Wendling286a0542008-12-02 06:24:20 +00004687 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004688 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004689 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004690 }
4691
4692 return 0;
4693}
4694
Chris Lattner7e708292002-06-25 16:13:24 +00004695Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004696 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004697 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004698
Chris Lattner42593e62007-03-24 23:56:43 +00004699 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004700 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004701
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004702 // or X, X = X
4703 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004704 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004705
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004706 // See if we can simplify any instructions used by the instruction whose sole
4707 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004708 if (SimplifyDemandedInstructionBits(I))
4709 return &I;
4710 if (isa<VectorType>(I.getType())) {
4711 if (isa<ConstantAggregateZero>(Op1)) {
4712 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4713 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4714 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4715 return ReplaceInstUsesWith(I, I.getOperand(1));
4716 }
Chris Lattner42593e62007-03-24 23:56:43 +00004717 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004718
Chris Lattner3f5b8772002-05-06 16:14:14 +00004719 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004720 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004721 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004722 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004723 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004724 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004725 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004726 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004727 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004728 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004729 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004730
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004731 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004732 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004733 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004734 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004735 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004736 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004737 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004738 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004739
4740 // Try to fold constant and into select arguments.
4741 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004742 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004743 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004744 if (isa<PHINode>(Op0))
4745 if (Instruction *NV = FoldOpIntoPhi(I))
4746 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004747 }
4748
Chris Lattner4f637d42006-01-06 17:59:59 +00004749 Value *A = 0, *B = 0;
4750 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004751
Dan Gohman4ae51262009-08-12 16:23:25 +00004752 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004753 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4754 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004755 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004756 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4757 return ReplaceInstUsesWith(I, Op0);
4758
Chris Lattner6423d4c2006-07-10 20:25:24 +00004759 // (A | B) | C and A | (B | C) -> bswap if possible.
4760 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004761 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4762 match(Op1, m_Or(m_Value(), m_Value())) ||
4763 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4764 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004765 if (Instruction *BSwap = MatchBSwap(I))
4766 return BSwap;
4767 }
4768
Chris Lattner6e4c6492005-05-09 04:58:36 +00004769 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004770 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004771 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004772 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004773 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004774 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004775 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004776 }
4777
4778 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004779 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004780 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004781 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004782 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004783 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004784 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004785 }
4786
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004787 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004788 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004789 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4790 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004791 Value *V1 = 0, *V2 = 0, *V3 = 0;
4792 C1 = dyn_cast<ConstantInt>(C);
4793 C2 = dyn_cast<ConstantInt>(D);
4794 if (C1 && C2) { // (A & C1)|(B & C2)
4795 // If we have: ((V + N) & C1) | (V & C2)
4796 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4797 // replace with V+N.
4798 if (C1->getValue() == ~C2->getValue()) {
4799 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004800 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004801 // Add commutes, try both ways.
4802 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4803 return ReplaceInstUsesWith(I, A);
4804 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4805 return ReplaceInstUsesWith(I, A);
4806 }
4807 // Or commutes, try both ways.
4808 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004809 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004810 // Add commutes, try both ways.
4811 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4812 return ReplaceInstUsesWith(I, B);
4813 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4814 return ReplaceInstUsesWith(I, B);
4815 }
4816 }
Chris Lattner044e5332007-04-08 08:01:49 +00004817 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004818 }
4819
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004820 // Check to see if we have any common things being and'ed. If so, find the
4821 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004822 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4823 if (A == B) // (A & C)|(A & D) == A & (C|D)
4824 V1 = A, V2 = C, V3 = D;
4825 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4826 V1 = A, V2 = B, V3 = C;
4827 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4828 V1 = C, V2 = A, V3 = D;
4829 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4830 V1 = C, V2 = A, V3 = B;
4831
4832 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004833 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004834 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004835 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004836 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004837
Dan Gohman1975d032008-10-30 20:40:10 +00004838 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004839 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004840 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004841 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004842 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004843 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004844 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004845 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004846 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004847
Bill Wendlingb01865c2008-11-30 13:52:49 +00004848 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004849 if ((match(C, m_Not(m_Specific(D))) &&
4850 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004851 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004852 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004853 if ((match(A, m_Not(m_Specific(D))) &&
4854 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004855 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004856 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004857 if ((match(C, m_Not(m_Specific(B))) &&
4858 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004859 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004860 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004861 if ((match(A, m_Not(m_Specific(B))) &&
4862 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004863 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004864 }
Chris Lattnere511b742006-11-14 07:46:50 +00004865
4866 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004867 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4868 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4869 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004870 SI0->getOperand(1) == SI1->getOperand(1) &&
4871 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004872 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4873 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004874 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004875 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004876 }
4877 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004878
Bill Wendlingb3833d12008-12-01 01:07:11 +00004879 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004880 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4881 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004882 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004883 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004884 }
4885 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004886 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4887 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004888 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004889 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004890 }
4891
Dan Gohman4ae51262009-08-12 16:23:25 +00004892 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004893 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004894 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004895 } else {
4896 A = 0;
4897 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004898 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004899 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004900 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004901 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004902
Misha Brukmancb6267b2004-07-30 12:50:08 +00004903 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004904 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004905 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004906 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004907 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004908 }
Chris Lattnera2881962003-02-18 19:28:33 +00004909
Reid Spencere4d87aa2006-12-23 06:05:41 +00004910 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4911 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004912 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004913 return R;
4914
Chris Lattner69d4ced2008-11-16 05:20:07 +00004915 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4916 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4917 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004918 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004919
4920 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004921 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004922 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004923 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004924 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4925 !isa<ICmpInst>(Op1C->getOperand(0))) {
4926 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004927 if (SrcTy == Op1C->getOperand(0)->getType() &&
4928 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004929 // Only do this if the casts both really cause code to be
4930 // generated.
4931 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4932 I.getType(), TD) &&
4933 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4934 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004935 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4936 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004937 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004938 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004939 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004940 }
Chris Lattner99c65742007-10-24 05:38:08 +00004941 }
4942
4943
4944 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4945 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004946 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4947 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4948 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004949 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004950
Chris Lattner7e708292002-06-25 16:13:24 +00004951 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004952}
4953
Dan Gohman844731a2008-05-13 00:00:25 +00004954namespace {
4955
Chris Lattnerc317d392004-02-16 01:20:27 +00004956// XorSelf - Implements: X ^ X --> 0
4957struct XorSelf {
4958 Value *RHS;
4959 XorSelf(Value *rhs) : RHS(rhs) {}
4960 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4961 Instruction *apply(BinaryOperator &Xor) const {
4962 return &Xor;
4963 }
4964};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004965
Dan Gohman844731a2008-05-13 00:00:25 +00004966}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004967
Chris Lattner7e708292002-06-25 16:13:24 +00004968Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004969 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004971
Evan Chengd34af782008-03-25 20:07:13 +00004972 if (isa<UndefValue>(Op1)) {
4973 if (isa<UndefValue>(Op0))
4974 // Handle undef ^ undef -> 0 special case. This is a common
4975 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00004976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004977 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004978 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004979
Chris Lattnerc317d392004-02-16 01:20:27 +00004980 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00004981 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004982 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00004983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004984 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004985
4986 // See if we can simplify any instructions used by the instruction whose sole
4987 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004988 if (SimplifyDemandedInstructionBits(I))
4989 return &I;
4990 if (isa<VectorType>(I.getType()))
4991 if (isa<ConstantAggregateZero>(Op1))
4992 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00004993
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004994 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00004995 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004996 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4997 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4998 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4999 if (Op0I->getOpcode() == Instruction::And ||
5000 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005001 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5002 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005003 Value *NotY =
5004 Builder->CreateNot(Op0I->getOperand(1),
5005 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005006 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005007 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005008 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005009 }
5010 }
5011 }
5012 }
5013
5014
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005015 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005016 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005017 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005018 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005019 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005020 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005021
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005022 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005023 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005024 FCI->getOperand(0), FCI->getOperand(1));
5025 }
5026
Nick Lewycky517e1f52008-05-31 19:01:33 +00005027 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5028 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5029 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5030 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5031 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005032 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5033 (RHS == ConstantExpr::getCast(Opcode,
5034 ConstantInt::getTrue(*Context),
5035 Op0C->getDestTy()))) {
5036 CI->setPredicate(CI->getInversePredicate());
5037 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005038 }
5039 }
5040 }
5041 }
5042
Reid Spencere4d87aa2006-12-23 06:05:41 +00005043 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005044 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005045 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5046 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005047 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5048 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005049 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005050 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005051 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005052
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005053 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005054 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005055 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005056 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005057 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005058 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005059 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005060 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005061 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005062 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005063 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005064 Constant *C = ConstantInt::get(*Context,
5065 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005066 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005067
Chris Lattner7c4049c2004-01-12 19:35:11 +00005068 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005069 } else if (Op0I->getOpcode() == Instruction::Or) {
5070 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005071 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005072 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005073 // Anything in both C1 and C2 is known to be zero, remove it from
5074 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005075 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5076 NewRHS = ConstantExpr::getAnd(NewRHS,
5077 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005078 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005079 I.setOperand(0, Op0I->getOperand(0));
5080 I.setOperand(1, NewRHS);
5081 return &I;
5082 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005083 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005084 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005085 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005086
5087 // Try to fold constant and into select arguments.
5088 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005089 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005090 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005091 if (isa<PHINode>(Op0))
5092 if (Instruction *NV = FoldOpIntoPhi(I))
5093 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005094 }
5095
Dan Gohman186a6362009-08-12 16:04:34 +00005096 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005097 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005098 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005099
Dan Gohman186a6362009-08-12 16:04:34 +00005100 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005101 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005102 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005103
Chris Lattner318bf792007-03-18 22:51:34 +00005104
5105 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5106 if (Op1I) {
5107 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005108 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005109 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005110 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005111 I.swapOperands();
5112 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005113 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005114 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005115 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005116 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005117 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005118 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005119 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005120 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005121 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005122 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005123 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005124 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005125 std::swap(A, B);
5126 }
Chris Lattner318bf792007-03-18 22:51:34 +00005127 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005128 I.swapOperands(); // Simplified below.
5129 std::swap(Op0, Op1);
5130 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005131 }
Chris Lattner318bf792007-03-18 22:51:34 +00005132 }
5133
5134 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5135 if (Op0I) {
5136 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005137 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005138 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005139 if (A == Op1) // (B|A)^B == (A|B)^B
5140 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005141 if (B == Op1) // (A|B)^B == A & ~B
5142 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005143 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005144 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005145 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005146 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005147 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005148 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005149 if (A == Op1) // (A&B)^A -> (B&A)^A
5150 std::swap(A, B);
5151 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005152 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005153 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005154 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005155 }
Chris Lattner318bf792007-03-18 22:51:34 +00005156 }
5157
5158 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5159 if (Op0I && Op1I && Op0I->isShift() &&
5160 Op0I->getOpcode() == Op1I->getOpcode() &&
5161 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5162 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005163 Value *NewOp =
5164 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5165 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005166 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005167 Op1I->getOperand(1));
5168 }
5169
5170 if (Op0I && Op1I) {
5171 Value *A, *B, *C, *D;
5172 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005173 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5174 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005175 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005176 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005177 }
5178 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005179 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5180 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005181 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005182 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005183 }
5184
5185 // (A & B)^(C & D)
5186 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005187 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5188 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005189 // (X & Y)^(X & Y) -> (Y^Z) & X
5190 Value *X = 0, *Y = 0, *Z = 0;
5191 if (A == C)
5192 X = A, Y = B, Z = D;
5193 else if (A == D)
5194 X = A, Y = B, Z = C;
5195 else if (B == C)
5196 X = B, Y = A, Z = D;
5197 else if (B == D)
5198 X = B, Y = A, Z = C;
5199
5200 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005201 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005202 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005203 }
5204 }
5205 }
5206
Reid Spencere4d87aa2006-12-23 06:05:41 +00005207 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5208 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005209 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005210 return R;
5211
Chris Lattner6fc205f2006-05-05 06:39:07 +00005212 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005213 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005214 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005215 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5216 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005217 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005218 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005219 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5220 I.getType(), TD) &&
5221 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5222 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005223 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5224 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005225 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005226 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005227 }
Chris Lattner99c65742007-10-24 05:38:08 +00005228 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005229
Chris Lattner7e708292002-06-25 16:13:24 +00005230 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005231}
5232
Owen Andersond672ecb2009-07-03 00:17:18 +00005233static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005234 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005235 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005236}
Chris Lattnera96879a2004-09-29 17:40:11 +00005237
Dan Gohman6de29f82009-06-15 22:12:54 +00005238static bool HasAddOverflow(ConstantInt *Result,
5239 ConstantInt *In1, ConstantInt *In2,
5240 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005241 if (IsSigned)
5242 if (In2->getValue().isNegative())
5243 return Result->getValue().sgt(In1->getValue());
5244 else
5245 return Result->getValue().slt(In1->getValue());
5246 else
5247 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005248}
5249
Dan Gohman6de29f82009-06-15 22:12:54 +00005250/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005251/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005252static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005253 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005254 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005255 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005256
Dan Gohman6de29f82009-06-15 22:12:54 +00005257 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5258 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005259 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005260 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5261 ExtractElement(In1, Idx, Context),
5262 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005263 IsSigned))
5264 return true;
5265 }
5266 return false;
5267 }
5268
5269 return HasAddOverflow(cast<ConstantInt>(Result),
5270 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5271 IsSigned);
5272}
5273
5274static bool HasSubOverflow(ConstantInt *Result,
5275 ConstantInt *In1, ConstantInt *In2,
5276 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005277 if (IsSigned)
5278 if (In2->getValue().isNegative())
5279 return Result->getValue().slt(In1->getValue());
5280 else
5281 return Result->getValue().sgt(In1->getValue());
5282 else
5283 return Result->getValue().ugt(In1->getValue());
5284}
5285
Dan Gohman6de29f82009-06-15 22:12:54 +00005286/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5287/// overflowed for this type.
5288static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005289 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005290 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005291 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005292
5293 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5294 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005295 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005296 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5297 ExtractElement(In1, Idx, Context),
5298 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005299 IsSigned))
5300 return true;
5301 }
5302 return false;
5303 }
5304
5305 return HasSubOverflow(cast<ConstantInt>(Result),
5306 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5307 IsSigned);
5308}
5309
Chris Lattner574da9b2005-01-13 20:14:25 +00005310/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5311/// code necessary to compute the offset from the base pointer (without adding
5312/// in the base pointer). Return the result as a signed integer of intptr size.
5313static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005314 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005315 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005316 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005317 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005318
5319 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005320 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005321 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005322
Gabor Greif177dd3f2008-06-12 21:37:33 +00005323 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5324 ++i, ++GTI) {
5325 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005326 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005327 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5328 if (OpC->isZero()) continue;
5329
5330 // Handle a struct index, which adds its field offset to the pointer.
5331 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5332 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5333
Chris Lattner74381062009-08-30 07:44:24 +00005334 Result = IC.Builder->CreateAdd(Result,
5335 ConstantInt::get(IntPtrTy, Size),
5336 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005337 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005338 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005339
Owen Andersoneed707b2009-07-24 23:12:02 +00005340 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005341 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005342 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5343 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005344 // Emit an add instruction.
5345 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005346 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005347 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005348 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005349 if (Op->getType() != IntPtrTy)
5350 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005351 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005352 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005353 // We'll let instcombine(mul) convert this to a shl if possible.
5354 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005355 }
5356
5357 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005358 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005359 }
5360 return Result;
5361}
5362
Chris Lattner10c0d912008-04-22 02:53:33 +00005363
Dan Gohman8f080f02009-07-17 22:16:21 +00005364/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5365/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5366/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5367/// be complex, and scales are involved. The above expression would also be
5368/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5369/// This later form is less amenable to optimization though, and we are allowed
5370/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005371///
5372/// If we can't emit an optimized form for this expression, this returns null.
5373///
5374static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5375 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005376 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005377 gep_type_iterator GTI = gep_type_begin(GEP);
5378
5379 // Check to see if this gep only has a single variable index. If so, and if
5380 // any constant indices are a multiple of its scale, then we can compute this
5381 // in terms of the scale of the variable index. For example, if the GEP
5382 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5383 // because the expression will cross zero at the same point.
5384 unsigned i, e = GEP->getNumOperands();
5385 int64_t Offset = 0;
5386 for (i = 1; i != e; ++i, ++GTI) {
5387 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5388 // Compute the aggregate offset of constant indices.
5389 if (CI->isZero()) continue;
5390
5391 // Handle a struct index, which adds its field offset to the pointer.
5392 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5393 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5394 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005395 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005396 Offset += Size*CI->getSExtValue();
5397 }
5398 } else {
5399 // Found our variable index.
5400 break;
5401 }
5402 }
5403
5404 // If there are no variable indices, we must have a constant offset, just
5405 // evaluate it the general way.
5406 if (i == e) return 0;
5407
5408 Value *VariableIdx = GEP->getOperand(i);
5409 // Determine the scale factor of the variable element. For example, this is
5410 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005411 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005412
5413 // Verify that there are no other variable indices. If so, emit the hard way.
5414 for (++i, ++GTI; i != e; ++i, ++GTI) {
5415 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5416 if (!CI) return 0;
5417
5418 // Compute the aggregate offset of constant indices.
5419 if (CI->isZero()) continue;
5420
5421 // Handle a struct index, which adds its field offset to the pointer.
5422 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5423 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5424 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005425 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005426 Offset += Size*CI->getSExtValue();
5427 }
5428 }
5429
5430 // Okay, we know we have a single variable index, which must be a
5431 // pointer/array/vector index. If there is no offset, life is simple, return
5432 // the index.
5433 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5434 if (Offset == 0) {
5435 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5436 // we don't need to bother extending: the extension won't affect where the
5437 // computation crosses zero.
5438 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005439 VariableIdx = new TruncInst(VariableIdx,
5440 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005441 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005442 return VariableIdx;
5443 }
5444
5445 // Otherwise, there is an index. The computation we will do will be modulo
5446 // the pointer size, so get it.
5447 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5448
5449 Offset &= PtrSizeMask;
5450 VariableScale &= PtrSizeMask;
5451
5452 // To do this transformation, any constant index must be a multiple of the
5453 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5454 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5455 // multiple of the variable scale.
5456 int64_t NewOffs = Offset / (int64_t)VariableScale;
5457 if (Offset != NewOffs*(int64_t)VariableScale)
5458 return 0;
5459
5460 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005461 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005462 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005463 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005464 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005465 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005466 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005467 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005468}
5469
5470
Reid Spencere4d87aa2006-12-23 06:05:41 +00005471/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005472/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005473Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005474 ICmpInst::Predicate Cond,
5475 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005476 // Look through bitcasts.
5477 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5478 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005479
Chris Lattner574da9b2005-01-13 20:14:25 +00005480 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005481 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005482 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005483 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005484 // know pointers can't overflow since the gep is inbounds. See if we can
5485 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005486 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5487
5488 // If not, synthesize the offset the hard way.
5489 if (Offset == 0)
5490 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005491 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005492 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005493 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005494 // If the base pointers are different, but the indices are the same, just
5495 // compare the base pointer.
5496 if (PtrBase != GEPRHS->getOperand(0)) {
5497 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005498 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005499 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005500 if (IndicesTheSame)
5501 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5502 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5503 IndicesTheSame = false;
5504 break;
5505 }
5506
5507 // If all indices are the same, just compare the base pointers.
5508 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005509 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005510 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005511
5512 // Otherwise, the base pointers are different and the indices are
5513 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005514 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005515 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005516
Chris Lattnere9d782b2005-01-13 22:25:21 +00005517 // If one of the GEPs has all zero indices, recurse.
5518 bool AllZeros = true;
5519 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5520 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5521 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5522 AllZeros = false;
5523 break;
5524 }
5525 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005526 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5527 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005528
5529 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005530 AllZeros = true;
5531 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5532 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5533 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5534 AllZeros = false;
5535 break;
5536 }
5537 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005538 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005539
Chris Lattner4401c9c2005-01-14 00:20:05 +00005540 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5541 // If the GEPs only differ by one index, compare it.
5542 unsigned NumDifferences = 0; // Keep track of # differences.
5543 unsigned DiffOperand = 0; // The operand that differs.
5544 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5545 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005546 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5547 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005548 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005549 NumDifferences = 2;
5550 break;
5551 } else {
5552 if (NumDifferences++) break;
5553 DiffOperand = i;
5554 }
5555 }
5556
5557 if (NumDifferences == 0) // SAME GEP?
5558 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005559 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005560 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005561
Chris Lattner4401c9c2005-01-14 00:20:05 +00005562 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005563 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5564 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005565 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005566 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005567 }
5568 }
5569
Reid Spencere4d87aa2006-12-23 06:05:41 +00005570 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005571 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005572 if (TD &&
5573 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005574 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5575 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5576 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5577 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005578 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005579 }
5580 }
5581 return 0;
5582}
5583
Chris Lattnera5406232008-05-19 20:18:56 +00005584/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5585///
5586Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5587 Instruction *LHSI,
5588 Constant *RHSC) {
5589 if (!isa<ConstantFP>(RHSC)) return 0;
5590 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5591
5592 // Get the width of the mantissa. We don't want to hack on conversions that
5593 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005594 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005595 if (MantissaWidth == -1) return 0; // Unknown.
5596
5597 // Check to see that the input is converted from an integer type that is small
5598 // enough that preserves all bits. TODO: check here for "known" sign bits.
5599 // 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 +00005600 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005601
5602 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005603 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5604 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005605 ++InputSize;
5606
5607 // If the conversion would lose info, don't hack on this.
5608 if ((int)InputSize > MantissaWidth)
5609 return 0;
5610
5611 // Otherwise, we can potentially simplify the comparison. We know that it
5612 // will always come through as an integer value and we know the constant is
5613 // not a NAN (it would have been previously simplified).
5614 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5615
5616 ICmpInst::Predicate Pred;
5617 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005618 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005619 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005620 case FCmpInst::FCMP_OEQ:
5621 Pred = ICmpInst::ICMP_EQ;
5622 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005623 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005624 case FCmpInst::FCMP_OGT:
5625 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5626 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005627 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005628 case FCmpInst::FCMP_OGE:
5629 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5630 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005631 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005632 case FCmpInst::FCMP_OLT:
5633 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5634 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005635 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005636 case FCmpInst::FCMP_OLE:
5637 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5638 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005639 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005640 case FCmpInst::FCMP_ONE:
5641 Pred = ICmpInst::ICMP_NE;
5642 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005643 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005644 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005645 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005646 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005647 }
5648
5649 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5650
5651 // Now we know that the APFloat is a normal number, zero or inf.
5652
Chris Lattner85162782008-05-20 03:50:52 +00005653 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005654 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005655 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005656
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005657 if (!LHSUnsigned) {
5658 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5659 // and large values.
5660 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5661 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5662 APFloat::rmNearestTiesToEven);
5663 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5664 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5665 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005666 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5667 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005668 }
5669 } else {
5670 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5671 // +INF and large values.
5672 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5673 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5674 APFloat::rmNearestTiesToEven);
5675 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5676 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5677 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005678 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5679 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005680 }
Chris Lattnera5406232008-05-19 20:18:56 +00005681 }
5682
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005683 if (!LHSUnsigned) {
5684 // See if the RHS value is < SignedMin.
5685 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5686 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5687 APFloat::rmNearestTiesToEven);
5688 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5689 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5690 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005691 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5692 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005693 }
Chris Lattnera5406232008-05-19 20:18:56 +00005694 }
5695
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005696 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5697 // [0, UMAX], but it may still be fractional. See if it is fractional by
5698 // casting the FP value to the integer value and back, checking for equality.
5699 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005700 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005701 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5702 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005703 if (!RHS.isZero()) {
5704 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005705 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5706 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005707 if (!Equal) {
5708 // If we had a comparison against a fractional value, we have to adjust
5709 // the compare predicate and sometimes the value. RHSC is rounded towards
5710 // zero at this point.
5711 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005712 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005713 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005714 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005715 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005716 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005717 case ICmpInst::ICMP_ULE:
5718 // (float)int <= 4.4 --> int <= 4
5719 // (float)int <= -4.4 --> false
5720 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005721 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005722 break;
5723 case ICmpInst::ICMP_SLE:
5724 // (float)int <= 4.4 --> int <= 4
5725 // (float)int <= -4.4 --> int < -4
5726 if (RHS.isNegative())
5727 Pred = ICmpInst::ICMP_SLT;
5728 break;
5729 case ICmpInst::ICMP_ULT:
5730 // (float)int < -4.4 --> false
5731 // (float)int < 4.4 --> int <= 4
5732 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005734 Pred = ICmpInst::ICMP_ULE;
5735 break;
5736 case ICmpInst::ICMP_SLT:
5737 // (float)int < -4.4 --> int < -4
5738 // (float)int < 4.4 --> int <= 4
5739 if (!RHS.isNegative())
5740 Pred = ICmpInst::ICMP_SLE;
5741 break;
5742 case ICmpInst::ICMP_UGT:
5743 // (float)int > 4.4 --> int > 4
5744 // (float)int > -4.4 --> true
5745 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005746 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005747 break;
5748 case ICmpInst::ICMP_SGT:
5749 // (float)int > 4.4 --> int > 4
5750 // (float)int > -4.4 --> int >= -4
5751 if (RHS.isNegative())
5752 Pred = ICmpInst::ICMP_SGE;
5753 break;
5754 case ICmpInst::ICMP_UGE:
5755 // (float)int >= -4.4 --> true
5756 // (float)int >= 4.4 --> int > 4
5757 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005758 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005759 Pred = ICmpInst::ICMP_UGT;
5760 break;
5761 case ICmpInst::ICMP_SGE:
5762 // (float)int >= -4.4 --> int >= -4
5763 // (float)int >= 4.4 --> int > 4
5764 if (!RHS.isNegative())
5765 Pred = ICmpInst::ICMP_SGT;
5766 break;
5767 }
Chris Lattnera5406232008-05-19 20:18:56 +00005768 }
5769 }
5770
5771 // Lower this FP comparison into an appropriate integer version of the
5772 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005773 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005774}
5775
Reid Spencere4d87aa2006-12-23 06:05:41 +00005776Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5777 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005778 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005779
Chris Lattner58e97462007-01-14 19:42:17 +00005780 // Fold trivial predicates.
5781 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005782 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005783 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005784 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005785
5786 // Simplify 'fcmp pred X, X'
5787 if (Op0 == Op1) {
5788 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005789 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005790 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5791 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5792 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005793 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005794 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5795 case FCmpInst::FCMP_OLT: // True if ordered and less than
5796 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005797 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005798
5799 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5800 case FCmpInst::FCMP_ULT: // True if unordered or less than
5801 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5802 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5803 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5804 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005805 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005806 return &I;
5807
5808 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5809 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5810 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5811 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5812 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5813 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005814 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005815 return &I;
5816 }
5817 }
5818
Reid Spencere4d87aa2006-12-23 06:05:41 +00005819 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005820 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005821
Reid Spencere4d87aa2006-12-23 06:05:41 +00005822 // Handle fcmp with constant RHS
5823 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005824 // If the constant is a nan, see if we can fold the comparison based on it.
5825 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5826 if (CFP->getValueAPF().isNaN()) {
5827 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005828 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005829 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5830 "Comparison must be either ordered or unordered!");
5831 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005832 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005833 }
5834 }
5835
Reid Spencere4d87aa2006-12-23 06:05:41 +00005836 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5837 switch (LHSI->getOpcode()) {
5838 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005839 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5840 // block. If in the same block, we're encouraging jump threading. If
5841 // not, we are just pessimizing the code by making an i1 phi.
5842 if (LHSI->getParent() == I.getParent())
5843 if (Instruction *NV = FoldOpIntoPhi(I))
5844 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005845 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005846 case Instruction::SIToFP:
5847 case Instruction::UIToFP:
5848 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5849 return NV;
5850 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005851 case Instruction::Select:
5852 // If either operand of the select is a constant, we can fold the
5853 // comparison into the select arms, which will cause one to be
5854 // constant folded and the select turned into a bitwise or.
5855 Value *Op1 = 0, *Op2 = 0;
5856 if (LHSI->hasOneUse()) {
5857 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5858 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005859 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005860 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005861 Op2 = Builder->CreateFCmp(I.getPredicate(),
5862 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005863 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5864 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005865 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005866 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005867 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5868 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005869 }
5870 }
5871
5872 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005873 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005874 break;
5875 }
5876 }
5877
5878 return Changed ? &I : 0;
5879}
5880
5881Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5882 bool Changed = SimplifyCompare(I);
5883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5884 const Type *Ty = Op0->getType();
5885
5886 // icmp X, X
5887 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00005888 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005889 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005890
5891 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005892 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005893
Reid Spencere4d87aa2006-12-23 06:05:41 +00005894 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005895 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005896 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5897 isa<ConstantPointerNull>(Op0)) &&
5898 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005899 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005900 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005901 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005902
Reid Spencere4d87aa2006-12-23 06:05:41 +00005903 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005904 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005905 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005906 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005907 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005908 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005909 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005910 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005911 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005912 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005913
Reid Spencere4d87aa2006-12-23 06:05:41 +00005914 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005915 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005916 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005917 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005918 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005919 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005920 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005921 case ICmpInst::ICMP_SGT:
5922 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005923 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005924 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005925 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005926 return BinaryOperator::CreateAnd(Not, Op0);
5927 }
5928 case ICmpInst::ICMP_UGE:
5929 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5930 // FALL THROUGH
5931 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005932 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005933 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005934 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005935 case ICmpInst::ICMP_SGE:
5936 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5937 // FALL THROUGH
5938 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005939 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005940 return BinaryOperator::CreateOr(Not, Op0);
5941 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005942 }
Chris Lattner8b170942002-08-09 23:47:40 +00005943 }
5944
Dan Gohman1c8491e2009-04-25 17:12:48 +00005945 unsigned BitWidth = 0;
5946 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005947 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5948 else if (Ty->isIntOrIntVector())
5949 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005950
5951 bool isSignBit = false;
5952
Dan Gohman81b28ce2008-09-16 18:46:06 +00005953 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005954 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005955 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005956
Chris Lattnerb6566012008-01-05 01:18:20 +00005957 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5958 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005959 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005960 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005961 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005962 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005963
Dan Gohman81b28ce2008-09-16 18:46:06 +00005964 // If we have an icmp le or icmp ge instruction, turn it into the
5965 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5966 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005967 switch (I.getPredicate()) {
5968 default: break;
5969 case ICmpInst::ICMP_ULE:
5970 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005971 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005972 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005973 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005974 case ICmpInst::ICMP_SLE:
5975 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005976 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005977 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005978 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005979 case ICmpInst::ICMP_UGE:
5980 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005981 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005982 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005983 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005984 case ICmpInst::ICMP_SGE:
5985 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005986 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005987 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005988 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005989 }
5990
Chris Lattner183661e2008-07-11 05:40:05 +00005991 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005992 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005993 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005994 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5995 }
5996
5997 // See if we can fold the comparison based on range information we can get
5998 // by checking whether bits are known to be zero or one in the input.
5999 if (BitWidth != 0) {
6000 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6001 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6002
6003 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006004 isSignBit ? APInt::getSignBit(BitWidth)
6005 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006006 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006007 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006008 if (SimplifyDemandedBits(I.getOperandUse(1),
6009 APInt::getAllOnesValue(BitWidth),
6010 Op1KnownZero, Op1KnownOne, 0))
6011 return &I;
6012
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006013 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006014 // in. Compute the Min, Max and RHS values based on the known bits. For the
6015 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006016 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6017 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6018 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6019 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6020 Op0Min, Op0Max);
6021 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6022 Op1Min, Op1Max);
6023 } else {
6024 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6025 Op0Min, Op0Max);
6026 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6027 Op1Min, Op1Max);
6028 }
6029
Chris Lattner183661e2008-07-11 05:40:05 +00006030 // If Min and Max are known to be the same, then SimplifyDemandedBits
6031 // figured out that the LHS is a constant. Just constant fold this now so
6032 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006033 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006034 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006035 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006036 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006037 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006038 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006039
Chris Lattner183661e2008-07-11 05:40:05 +00006040 // Based on the range information we know about the LHS, see if we can
6041 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006042 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006043 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006044 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006045 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006046 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006047 break;
6048 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006050 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006051 break;
6052 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006053 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006054 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006055 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006056 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006057 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006058 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006059 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6060 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006061 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006062 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006063
6064 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6065 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006066 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006067 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006068 }
Chris Lattner84dff672008-07-11 05:08:55 +00006069 break;
6070 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006071 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006072 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006073 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006074 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006075
6076 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006077 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006078 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6079 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006080 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006081 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082
6083 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6084 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006085 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006086 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006087 }
Chris Lattner84dff672008-07-11 05:08:55 +00006088 break;
6089 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006091 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006092 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006093 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006095 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6097 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006098 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006099 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100 }
Chris Lattner84dff672008-07-11 05:08:55 +00006101 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006102 case ICmpInst::ICMP_SGT:
6103 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006104 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006106 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107
6108 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006109 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6111 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006112 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006113 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 }
6115 break;
6116 case ICmpInst::ICMP_SGE:
6117 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6118 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006119 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006121 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006122 break;
6123 case ICmpInst::ICMP_SLE:
6124 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6125 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006126 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006128 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 break;
6130 case ICmpInst::ICMP_UGE:
6131 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6132 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006133 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006134 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006135 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006136 break;
6137 case ICmpInst::ICMP_ULE:
6138 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6139 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006140 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006142 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006143 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006144 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145
6146 // Turn a signed comparison into an unsigned one if both operands
6147 // are known to have the same sign.
6148 if (I.isSignedPredicate() &&
6149 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6150 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006151 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006152 }
6153
6154 // Test if the ICmpInst instruction is used exclusively by a select as
6155 // part of a minimum or maximum operation. If so, refrain from doing
6156 // any other folding. This helps out other analyses which understand
6157 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6158 // and CodeGen. And in this case, at least one of the comparison
6159 // operands has at least one user besides the compare (the select),
6160 // which would often largely negate the benefit of folding anyway.
6161 if (I.hasOneUse())
6162 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6163 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6164 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6165 return 0;
6166
6167 // See if we are doing a comparison between a constant and an instruction that
6168 // can be folded into the comparison.
6169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006170 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006171 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006172 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006173 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006174 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6175 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006176 }
6177
Chris Lattner01deb9d2007-04-03 17:43:25 +00006178 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006179 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6180 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6181 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006182 case Instruction::GetElementPtr:
6183 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006184 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006185 bool isAllZeros = true;
6186 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6187 if (!isa<Constant>(LHSI->getOperand(i)) ||
6188 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6189 isAllZeros = false;
6190 break;
6191 }
6192 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006193 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006194 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006195 }
6196 break;
6197
Chris Lattner6970b662005-04-23 15:31:55 +00006198 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006199 // Only fold icmp into the PHI if the phi and fcmp are in the same
6200 // block. If in the same block, we're encouraging jump threading. If
6201 // not, we are just pessimizing the code by making an i1 phi.
6202 if (LHSI->getParent() == I.getParent())
6203 if (Instruction *NV = FoldOpIntoPhi(I))
6204 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006205 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006206 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006207 // If either operand of the select is a constant, we can fold the
6208 // comparison into the select arms, which will cause one to be
6209 // constant folded and the select turned into a bitwise or.
6210 Value *Op1 = 0, *Op2 = 0;
6211 if (LHSI->hasOneUse()) {
6212 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6213 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006214 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006215 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006216 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6217 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006218 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6219 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006220 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006221 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006222 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6223 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006224 }
6225 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006226
Chris Lattner6970b662005-04-23 15:31:55 +00006227 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006228 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006229 break;
6230 }
Chris Lattner4802d902007-04-06 18:57:34 +00006231 case Instruction::Malloc:
6232 // If we have (malloc != null), and if the malloc has a single use, we
6233 // can assume it is successful and remove the malloc.
6234 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006235 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006236 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006237 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006238 }
6239 break;
6240 }
Chris Lattner6970b662005-04-23 15:31:55 +00006241 }
6242
Reid Spencere4d87aa2006-12-23 06:05:41 +00006243 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006244 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006245 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006246 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006247 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006248 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6249 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006250 return NI;
6251
Reid Spencere4d87aa2006-12-23 06:05:41 +00006252 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006253 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6254 // now.
6255 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6256 if (isa<PointerType>(Op0->getType()) &&
6257 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006258 // We keep moving the cast from the left operand over to the right
6259 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006260 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006261
Chris Lattner57d86372007-01-06 01:45:59 +00006262 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6263 // so eliminate it as well.
6264 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6265 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006266
Chris Lattnerde90b762003-11-03 04:25:02 +00006267 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006268 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006269 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006270 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006271 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006272 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006273 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006274 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006275 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006276 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006277 }
Chris Lattner57d86372007-01-06 01:45:59 +00006278 }
6279
6280 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006282 // This comes up when you have code like
6283 // int X = A < B;
6284 // if (X) ...
6285 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006286 // with a constant or another cast from the same type.
6287 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006288 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006289 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006290 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006291
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006292 // See if it's the same type of instruction on the left and right.
6293 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6294 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006295 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006296 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006297 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006298 default: break;
6299 case Instruction::Add:
6300 case Instruction::Sub:
6301 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006302 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006303 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006304 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006305 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6306 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6307 if (CI->getValue().isSignBit()) {
6308 ICmpInst::Predicate Pred = I.isSignedPredicate()
6309 ? I.getUnsignedPredicate()
6310 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006311 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006312 Op1I->getOperand(0));
6313 }
6314
6315 if (CI->getValue().isMaxSignedValue()) {
6316 ICmpInst::Predicate Pred = I.isSignedPredicate()
6317 ? I.getUnsignedPredicate()
6318 : I.getSignedPredicate();
6319 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006320 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006321 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006322 }
6323 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006324 break;
6325 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006326 if (!I.isEquality())
6327 break;
6328
Nick Lewycky5d52c452008-08-21 05:56:10 +00006329 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6330 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6331 // Mask = -1 >> count-trailing-zeros(Cst).
6332 if (!CI->isZero() && !CI->isOne()) {
6333 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006334 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006335 APInt::getLowBitsSet(AP.getBitWidth(),
6336 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006337 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006338 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6339 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006340 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006341 }
6342 }
6343 break;
6344 }
6345 }
6346 }
6347 }
6348
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006349 // ~x < ~y --> y < x
6350 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006351 if (match(Op0, m_Not(m_Value(A))) &&
6352 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006353 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006354 }
6355
Chris Lattner65b72ba2006-09-18 04:22:48 +00006356 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006357 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006358
6359 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006360 if (match(Op0, m_Neg(m_Value(A))) &&
6361 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006362 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006363
Dan Gohman4ae51262009-08-12 16:23:25 +00006364 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006365 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6366 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006367 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006368 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006369 }
6370
Dan Gohman4ae51262009-08-12 16:23:25 +00006371 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006372 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006373 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006374 if (match(B, m_ConstantInt(C1)) &&
6375 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006376 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006377 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006378 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6379 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006380 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006381
6382 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006383 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6384 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6385 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6386 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006387 }
6388 }
6389
Dan Gohman4ae51262009-08-12 16:23:25 +00006390 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006391 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006392 // A == (A^B) -> B == 0
6393 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006394 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006395 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006396 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006397
6398 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006399 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006400 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006401 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006402
6403 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006404 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006405 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006406 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006407
Chris Lattner9c2328e2006-11-14 06:06:06 +00006408 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6409 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006410 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6411 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006412 Value *X = 0, *Y = 0, *Z = 0;
6413
6414 if (A == C) {
6415 X = B; Y = D; Z = A;
6416 } else if (A == D) {
6417 X = B; Y = C; Z = A;
6418 } else if (B == C) {
6419 X = A; Y = D; Z = B;
6420 } else if (B == D) {
6421 X = A; Y = C; Z = B;
6422 }
6423
6424 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006425 Op1 = Builder->CreateXor(X, Y, "tmp");
6426 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006427 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006428 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006429 return &I;
6430 }
6431 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006432 }
Chris Lattner7e708292002-06-25 16:13:24 +00006433 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006434}
6435
Chris Lattner562ef782007-06-20 23:46:26 +00006436
6437/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6438/// and CmpRHS are both known to be integer constants.
6439Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6440 ConstantInt *DivRHS) {
6441 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6442 const APInt &CmpRHSV = CmpRHS->getValue();
6443
6444 // FIXME: If the operand types don't match the type of the divide
6445 // then don't attempt this transform. The code below doesn't have the
6446 // logic to deal with a signed divide and an unsigned compare (and
6447 // vice versa). This is because (x /s C1) <s C2 produces different
6448 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6449 // (x /u C1) <u C2. Simply casting the operands and result won't
6450 // work. :( The if statement below tests that condition and bails
6451 // if it finds it.
6452 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6453 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6454 return 0;
6455 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006456 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006457 if (DivIsSigned && DivRHS->isAllOnesValue())
6458 return 0; // The overflow computation also screws up here
6459 if (DivRHS->isOne())
6460 return 0; // Not worth bothering, and eliminates some funny cases
6461 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006462
6463 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6464 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6465 // C2 (CI). By solving for X we can turn this into a range check
6466 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006467 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006468
6469 // Determine if the product overflows by seeing if the product is
6470 // not equal to the divide. Make sure we do the same kind of divide
6471 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006472 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6473 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006474
6475 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006476 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006477
Chris Lattner1dbfd482007-06-21 18:11:19 +00006478 // Figure out the interval that is being checked. For example, a comparison
6479 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6480 // Compute this interval based on the constants involved and the signedness of
6481 // the compare/divide. This computes a half-open interval, keeping track of
6482 // whether either value in the interval overflows. After analysis each
6483 // overflow variable is set to 0 if it's corresponding bound variable is valid
6484 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6485 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006486 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006487
Chris Lattner562ef782007-06-20 23:46:26 +00006488 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006489 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006490 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006491 HiOverflow = LoOverflow = ProdOV;
6492 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006493 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006494 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006495 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006496 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006497 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006498 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006499 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006500 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6501 HiOverflow = LoOverflow = ProdOV;
6502 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006503 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006504 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006505 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006506 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006507 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6508 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006509 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006510 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006511 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006512 true) ? -1 : 0;
6513 }
Chris Lattner562ef782007-06-20 23:46:26 +00006514 }
Dan Gohman76491272008-02-13 22:09:18 +00006515 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006516 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006517 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006518 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006519 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006520 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6521 HiOverflow = 1; // [INTMIN+1, overflow)
6522 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6523 }
Dan Gohman76491272008-02-13 22:09:18 +00006524 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006525 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006526 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006527 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006528 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006529 LoOverflow = AddWithOverflow(LoBound, HiBound,
6530 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006531 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006532 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6533 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006534 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006535 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006536 }
6537
Chris Lattner1dbfd482007-06-21 18:11:19 +00006538 // Dividing by a negative swaps the condition. LT <-> GT
6539 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006540 }
6541
6542 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006543 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006544 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006545 case ICmpInst::ICMP_EQ:
6546 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006547 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006548 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006549 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006550 ICmpInst::ICMP_UGE, X, LoBound);
6551 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006552 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006553 ICmpInst::ICMP_ULT, X, HiBound);
6554 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006555 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006556 case ICmpInst::ICMP_NE:
6557 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006558 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006559 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006560 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006561 ICmpInst::ICMP_ULT, X, LoBound);
6562 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006563 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006564 ICmpInst::ICMP_UGE, X, HiBound);
6565 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006566 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006567 case ICmpInst::ICMP_ULT:
6568 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006569 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006570 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006571 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006572 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006573 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006574 case ICmpInst::ICMP_UGT:
6575 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006576 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006577 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006578 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006579 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006581 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006582 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006583 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006584 }
6585}
6586
6587
Chris Lattner01deb9d2007-04-03 17:43:25 +00006588/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6589///
6590Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6591 Instruction *LHSI,
6592 ConstantInt *RHS) {
6593 const APInt &RHSV = RHS->getValue();
6594
6595 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006596 case Instruction::Trunc:
6597 if (ICI.isEquality() && LHSI->hasOneUse()) {
6598 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6599 // of the high bits truncated out of x are known.
6600 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6601 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6602 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6603 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6604 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6605
6606 // If all the high bits are known, we can do this xform.
6607 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6608 // Pull in the high bits from known-ones set.
6609 APInt NewRHS(RHS->getValue());
6610 NewRHS.zext(SrcBits);
6611 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006612 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006613 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006614 }
6615 }
6616 break;
6617
Duncan Sands0091bf22007-04-04 06:42:45 +00006618 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006619 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6620 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6621 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006622 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6623 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006624 Value *CompareVal = LHSI->getOperand(0);
6625
6626 // If the sign bit of the XorCST is not set, there is no change to
6627 // the operation, just stop using the Xor.
6628 if (!XorCST->getValue().isNegative()) {
6629 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006630 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006631 return &ICI;
6632 }
6633
6634 // Was the old condition true if the operand is positive?
6635 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6636
6637 // If so, the new one isn't.
6638 isTrueIfPositive ^= true;
6639
6640 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006641 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006642 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006643 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006644 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006645 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006646 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006647
6648 if (LHSI->hasOneUse()) {
6649 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6650 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6651 const APInt &SignBit = XorCST->getValue();
6652 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6653 ? ICI.getUnsignedPredicate()
6654 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006655 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006656 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006657 }
6658
6659 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006660 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006661 const APInt &NotSignBit = XorCST->getValue();
6662 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6663 ? ICI.getUnsignedPredicate()
6664 : ICI.getSignedPredicate();
6665 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006666 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006667 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006668 }
6669 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006670 }
6671 break;
6672 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6673 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6674 LHSI->getOperand(0)->hasOneUse()) {
6675 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6676
6677 // If the LHS is an AND of a truncating cast, we can widen the
6678 // and/compare to be the input width without changing the value
6679 // produced, eliminating a cast.
6680 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6681 // We can do this transformation if either the AND constant does not
6682 // have its sign bit set or if it is an equality comparison.
6683 // Extending a relational comparison when we're checking the sign
6684 // bit would not work.
6685 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006686 (ICI.isEquality() ||
6687 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006688 uint32_t BitWidth =
6689 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6690 APInt NewCST = AndCST->getValue();
6691 NewCST.zext(BitWidth);
6692 APInt NewCI = RHSV;
6693 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006694 Value *NewAnd =
6695 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006696 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006697 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006698 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006699 }
6700 }
6701
6702 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6703 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6704 // happens a LOT in code produced by the C front-end, for bitfield
6705 // access.
6706 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6707 if (Shift && !Shift->isShift())
6708 Shift = 0;
6709
6710 ConstantInt *ShAmt;
6711 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6712 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6713 const Type *AndTy = AndCST->getType(); // Type of the and.
6714
6715 // We can fold this as long as we can't shift unknown bits
6716 // into the mask. This can only happen with signed shift
6717 // rights, as they sign-extend.
6718 if (ShAmt) {
6719 bool CanFold = Shift->isLogicalShift();
6720 if (!CanFold) {
6721 // To test for the bad case of the signed shr, see if any
6722 // of the bits shifted in could be tested after the mask.
6723 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6724 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6725
6726 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6727 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6728 AndCST->getValue()) == 0)
6729 CanFold = true;
6730 }
6731
6732 if (CanFold) {
6733 Constant *NewCst;
6734 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006735 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006736 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006737 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006738
6739 // Check to see if we are shifting out any of the bits being
6740 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006741 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006742 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006743 // If we shifted bits out, the fold is not going to work out.
6744 // As a special case, check to see if this means that the
6745 // result is always true or false now.
6746 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006747 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006748 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006749 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006750 } else {
6751 ICI.setOperand(1, NewCst);
6752 Constant *NewAndCST;
6753 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006754 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006755 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006756 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757 LHSI->setOperand(1, NewAndCST);
6758 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006759 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006760 return &ICI;
6761 }
6762 }
6763 }
6764
6765 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6766 // preferable because it allows the C<<Y expression to be hoisted out
6767 // of a loop if Y is invariant and X is not.
6768 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006769 ICI.isEquality() && !Shift->isArithmeticShift() &&
6770 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006771 // Compute C << Y.
6772 Value *NS;
6773 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006774 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775 } else {
6776 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006777 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006778 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006779
6780 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006781 Value *NewAnd =
6782 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006783
6784 ICI.setOperand(0, NewAnd);
6785 return &ICI;
6786 }
6787 }
6788 break;
6789
Chris Lattnera0141b92007-07-15 20:42:37 +00006790 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6791 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6792 if (!ShAmt) break;
6793
6794 uint32_t TypeBits = RHSV.getBitWidth();
6795
6796 // Check that the shift amount is in range. If not, don't perform
6797 // undefined shifts. When the shift is visited it will be
6798 // simplified.
6799 if (ShAmt->uge(TypeBits))
6800 break;
6801
6802 if (ICI.isEquality()) {
6803 // If we are comparing against bits always shifted out, the
6804 // comparison cannot succeed.
6805 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006806 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006807 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006808 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6809 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006810 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006811 return ReplaceInstUsesWith(ICI, Cst);
6812 }
6813
6814 if (LHSI->hasOneUse()) {
6815 // Otherwise strength reduce the shift into an and.
6816 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6817 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006818 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006819 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006820
Chris Lattner74381062009-08-30 07:44:24 +00006821 Value *And =
6822 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006823 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006824 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006825 }
6826 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006827
6828 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6829 bool TrueIfSigned = false;
6830 if (LHSI->hasOneUse() &&
6831 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6832 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006833 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006834 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006835 Value *And =
6836 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006837 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006838 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006839 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006840 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006841 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006842
6843 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006844 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006845 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006846 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006847 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006848
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006849 // Check that the shift amount is in range. If not, don't perform
6850 // undefined shifts. When the shift is visited it will be
6851 // simplified.
6852 uint32_t TypeBits = RHSV.getBitWidth();
6853 if (ShAmt->uge(TypeBits))
6854 break;
6855
6856 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006857
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006858 // If we are comparing against bits always shifted out, the
6859 // comparison cannot succeed.
6860 APInt Comp = RHSV << ShAmtVal;
6861 if (LHSI->getOpcode() == Instruction::LShr)
6862 Comp = Comp.lshr(ShAmtVal);
6863 else
6864 Comp = Comp.ashr(ShAmtVal);
6865
6866 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6867 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006868 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006869 return ReplaceInstUsesWith(ICI, Cst);
6870 }
6871
6872 // Otherwise, check to see if the bits shifted out are known to be zero.
6873 // If so, we can compare against the unshifted value:
6874 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006875 if (LHSI->hasOneUse() &&
6876 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006877 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006878 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006879 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006880 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006881
Evan Chengf30752c2008-04-23 00:38:06 +00006882 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006883 // Otherwise strength reduce the shift into an and.
6884 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006885 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006886
Chris Lattner74381062009-08-30 07:44:24 +00006887 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6888 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006889 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006890 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006891 }
6892 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006893 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006894
6895 case Instruction::SDiv:
6896 case Instruction::UDiv:
6897 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6898 // Fold this div into the comparison, producing a range check.
6899 // Determine, based on the divide type, what the range is being
6900 // checked. If there is an overflow on the low or high side, remember
6901 // it, otherwise compute the range [low, hi) bounding the new value.
6902 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006903 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6904 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6905 DivRHS))
6906 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006908
6909 case Instruction::Add:
6910 // Fold: icmp pred (add, X, C1), C2
6911
6912 if (!ICI.isEquality()) {
6913 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6914 if (!LHSC) break;
6915 const APInt &LHSV = LHSC->getValue();
6916
6917 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6918 .subtract(LHSV);
6919
6920 if (ICI.isSignedPredicate()) {
6921 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006922 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006923 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006924 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006925 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006926 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006927 }
6928 } else {
6929 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006930 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006931 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006932 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006933 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006934 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006935 }
6936 }
6937 }
6938 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006939 }
6940
6941 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6942 if (ICI.isEquality()) {
6943 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6944
6945 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6946 // the second operand is a constant, simplify a bit.
6947 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6948 switch (BO->getOpcode()) {
6949 case Instruction::SRem:
6950 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6951 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6952 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6953 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006954 Value *NewRem =
6955 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6956 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006957 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006958 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006959 }
6960 }
6961 break;
6962 case Instruction::Add:
6963 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6964 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6965 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006966 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006967 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006968 } else if (RHSV == 0) {
6969 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6970 // efficiently invertible, or if the add has just this one use.
6971 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6972
Dan Gohman186a6362009-08-12 16:04:34 +00006973 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006974 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00006975 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006976 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00006978 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006979 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006980 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006981 }
6982 }
6983 break;
6984 case Instruction::Xor:
6985 // For the xor case, we can xor two constants together, eliminating
6986 // the explicit xor.
6987 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006988 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006989 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006990
6991 // FALLTHROUGH
6992 case Instruction::Sub:
6993 // Replace (([sub|xor] A, B) != 0) with (A != B)
6994 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006995 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006996 BO->getOperand(1));
6997 break;
6998
6999 case Instruction::Or:
7000 // If bits are being or'd in that are not present in the constant we
7001 // are comparing against, then the comparison could never succeed!
7002 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007003 Constant *NotCI = ConstantExpr::getNot(RHS);
7004 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007005 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007006 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007007 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007008 }
7009 break;
7010
7011 case Instruction::And:
7012 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7013 // If bits are being compared against that are and'd out, then the
7014 // comparison can never succeed!
7015 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007016 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007017 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007018 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019
7020 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7021 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007022 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007023 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007024 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007025
7026 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007027 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007028 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007029 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007030 ICmpInst::Predicate pred = isICMP_NE ?
7031 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007032 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007033 }
7034
7035 // ((X & ~7) == 0) --> X < 8
7036 if (RHSV == 0 && isHighOnes(BOC)) {
7037 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007038 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007039 ICmpInst::Predicate pred = isICMP_NE ?
7040 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007041 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007042 }
7043 }
7044 default: break;
7045 }
7046 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7047 // Handle icmp {eq|ne} <intrinsic>, intcst.
7048 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007049 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007050 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007051 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007052 return &ICI;
7053 }
7054 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007055 }
7056 return 0;
7057}
7058
7059/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7060/// We only handle extending casts so far.
7061///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007062Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7063 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007064 Value *LHSCIOp = LHSCI->getOperand(0);
7065 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007066 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007067 Value *RHSCIOp;
7068
Chris Lattner8c756c12007-05-05 22:41:33 +00007069 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7070 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007071 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7072 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007073 cast<IntegerType>(DestTy)->getBitWidth()) {
7074 Value *RHSOp = 0;
7075 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007076 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007077 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7078 RHSOp = RHSC->getOperand(0);
7079 // If the pointer types don't match, insert a bitcast.
7080 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007081 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007082 }
7083
7084 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007085 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007086 }
7087
7088 // The code below only handles extension cast instructions, so far.
7089 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007090 if (LHSCI->getOpcode() != Instruction::ZExt &&
7091 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007092 return 0;
7093
Reid Spencere4d87aa2006-12-23 06:05:41 +00007094 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7095 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007096
Reid Spencere4d87aa2006-12-23 06:05:41 +00007097 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007098 // Not an extension from the same type?
7099 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007100 if (RHSCIOp->getType() != LHSCIOp->getType())
7101 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007102
Nick Lewycky4189a532008-01-28 03:48:02 +00007103 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007104 // and the other is a zext), then we can't handle this.
7105 if (CI->getOpcode() != LHSCI->getOpcode())
7106 return 0;
7107
Nick Lewycky4189a532008-01-28 03:48:02 +00007108 // Deal with equality cases early.
7109 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007110 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007111
7112 // A signed comparison of sign extended values simplifies into a
7113 // signed comparison.
7114 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007115 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007116
7117 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007118 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007119 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007120
Reid Spencere4d87aa2006-12-23 06:05:41 +00007121 // If we aren't dealing with a constant on the RHS, exit early
7122 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7123 if (!CI)
7124 return 0;
7125
7126 // Compute the constant that would happen if we truncated to SrcTy then
7127 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007128 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7129 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007130 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007131
7132 // If the re-extended constant didn't change...
7133 if (Res2 == CI) {
7134 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7135 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007136 // %A = sext i16 %X to i32
7137 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007138 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007139 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007140 // because %A may have negative value.
7141 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007142 // However, we allow this when the compare is EQ/NE, because they are
7143 // signless.
7144 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007145 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007146 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007147 }
7148
7149 // The re-extended constant changed so the constant cannot be represented
7150 // in the shorter type. Consequently, we cannot emit a simple comparison.
7151
7152 // First, handle some easy cases. We know the result cannot be equal at this
7153 // point so handle the ICI.isEquality() cases
7154 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007155 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007156 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007157 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007158
7159 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7160 // should have been folded away previously and not enter in here.
7161 Value *Result;
7162 if (isSignedCmp) {
7163 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007164 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007165 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007166 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007167 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007168 } else {
7169 // We're performing an unsigned comparison.
7170 if (isSignedExt) {
7171 // We're performing an unsigned comp with a sign extended value.
7172 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007173 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007174 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007175 } else {
7176 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007177 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007178 }
7179 }
7180
7181 // Finally, return the value computed.
7182 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007183 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007184 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007185
7186 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7187 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7188 "ICmp should be folded!");
7189 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007190 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007191 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007192}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007193
Reid Spencer832254e2007-02-02 02:16:23 +00007194Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7195 return commonShiftTransforms(I);
7196}
7197
7198Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7199 return commonShiftTransforms(I);
7200}
7201
7202Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007203 if (Instruction *R = commonShiftTransforms(I))
7204 return R;
7205
7206 Value *Op0 = I.getOperand(0);
7207
7208 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7209 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7210 if (CSI->isAllOnesValue())
7211 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007212
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007213 // See if we can turn a signed shr into an unsigned shr.
7214 if (MaskedValueIsZero(Op0,
7215 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7216 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7217
7218 // Arithmetic shifting an all-sign-bit value is a no-op.
7219 unsigned NumSignBits = ComputeNumSignBits(Op0);
7220 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7221 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007222
Chris Lattner348f6652007-12-06 01:59:46 +00007223 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007224}
7225
7226Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7227 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007229
7230 // shl X, 0 == X and shr X, 0 == X
7231 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007232 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7233 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007234 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007235
Reid Spencere4d87aa2006-12-23 06:05:41 +00007236 if (isa<UndefValue>(Op0)) {
7237 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007238 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007239 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007240 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007241 }
7242 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007243 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7244 return ReplaceInstUsesWith(I, Op0);
7245 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007246 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007247 }
7248
Dan Gohman9004c8a2009-05-21 02:28:33 +00007249 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007250 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007251 return &I;
7252
Chris Lattner2eefe512004-04-09 19:05:30 +00007253 // Try to fold constant and into select arguments.
7254 if (isa<Constant>(Op0))
7255 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007256 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007257 return R;
7258
Reid Spencerb83eb642006-10-20 07:07:24 +00007259 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007260 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7261 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007262 return 0;
7263}
7264
Reid Spencerb83eb642006-10-20 07:07:24 +00007265Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007266 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007267 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007268
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007269 // See if we can simplify any instructions used by the instruction whose sole
7270 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007271 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007272
Dan Gohmana119de82009-06-14 23:30:43 +00007273 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7274 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007275 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007276 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007277 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007278 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007279 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007280 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007281 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007282 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007283 }
7284
7285 // ((X*C1) << C2) == (X * (C1 << C2))
7286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7287 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7288 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007289 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007290 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007291
7292 // Try to fold constant and into select arguments.
7293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7294 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7295 return R;
7296 if (isa<PHINode>(Op0))
7297 if (Instruction *NV = FoldOpIntoPhi(I))
7298 return NV;
7299
Chris Lattner8999dd32007-12-22 09:07:47 +00007300 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7301 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7302 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7303 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7304 // place. Don't try to do this transformation in this case. Also, we
7305 // require that the input operand is a shift-by-constant so that we have
7306 // confidence that the shifts will get folded together. We could do this
7307 // xform in more cases, but it is unlikely to be profitable.
7308 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7309 isa<ConstantInt>(TrOp->getOperand(1))) {
7310 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007311 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007312 // (shift2 (shift1 & 0x00FF), c2)
7313 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007314
7315 // For logical shifts, the truncation has the effect of making the high
7316 // part of the register be zeros. Emulate this by inserting an AND to
7317 // clear the top bits as needed. This 'and' will usually be zapped by
7318 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007319 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7320 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007321 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7322
7323 // The mask we constructed says what the trunc would do if occurring
7324 // between the shifts. We want to know the effect *after* the second
7325 // shift. We know that it is a logical shift by a constant, so adjust the
7326 // mask as appropriate.
7327 if (I.getOpcode() == Instruction::Shl)
7328 MaskV <<= Op1->getZExtValue();
7329 else {
7330 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7331 MaskV = MaskV.lshr(Op1->getZExtValue());
7332 }
7333
Chris Lattner74381062009-08-30 07:44:24 +00007334 // shift1 & 0x00FF
7335 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7336 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007337
7338 // Return the value truncated to the interesting size.
7339 return new TruncInst(And, I.getType());
7340 }
7341 }
7342
Chris Lattner4d5542c2006-01-06 07:12:35 +00007343 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007344 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7345 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7346 Value *V1, *V2;
7347 ConstantInt *CC;
7348 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007349 default: break;
7350 case Instruction::Add:
7351 case Instruction::And:
7352 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007353 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007354 // These operators commute.
7355 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007356 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007357 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007358 m_Specific(Op1)))) {
7359 Value *YS = // (Y << C)
7360 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7361 // (X + (Y << C))
7362 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7363 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007364 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007365 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007366 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007367 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007368
Chris Lattner150f12a2005-09-18 06:30:59 +00007369 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007370 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007371 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007372 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007373 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007374 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007375 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007376 Value *YS = // (Y << C)
7377 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7378 Op0BO->getName());
7379 // X & (CC << C)
7380 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7381 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007382 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007383 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007384 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007385
Reid Spencera07cb7d2007-02-02 14:41:37 +00007386 // FALL THROUGH.
7387 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007388 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007389 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007390 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007391 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007392 Value *YS = // (Y << C)
7393 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7394 // (X + (Y << C))
7395 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7396 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007397 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007398 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007399 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007400 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007401
Chris Lattner13d4ab42006-05-31 21:14:00 +00007402 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007403 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7404 match(Op0BO->getOperand(0),
7405 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007406 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007407 cast<BinaryOperator>(Op0BO->getOperand(0))
7408 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007409 Value *YS = // (Y << C)
7410 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7411 // X & (CC << C)
7412 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7413 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007414
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007415 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007416 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007417
Chris Lattner11021cb2005-09-18 05:12:10 +00007418 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007419 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007420 }
7421
7422
7423 // If the operand is an bitwise operator with a constant RHS, and the
7424 // shift is the only use, we can pull it out of the shift.
7425 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7426 bool isValid = true; // Valid only for And, Or, Xor
7427 bool highBitSet = false; // Transform if high bit of constant set?
7428
7429 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007430 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007431 case Instruction::Add:
7432 isValid = isLeftShift;
7433 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007434 case Instruction::Or:
7435 case Instruction::Xor:
7436 highBitSet = false;
7437 break;
7438 case Instruction::And:
7439 highBitSet = true;
7440 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007441 }
7442
7443 // If this is a signed shift right, and the high bit is modified
7444 // by the logical operation, do not perform the transformation.
7445 // The highBitSet boolean indicates the value of the high bit of
7446 // the constant which would cause it to be modified for this
7447 // operation.
7448 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007449 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007450 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007451
7452 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007453 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007454
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007455 Value *NewShift =
7456 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007457 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007458
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007459 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007460 NewRHS);
7461 }
7462 }
7463 }
7464 }
7465
Chris Lattnerad0124c2006-01-06 07:52:12 +00007466 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007467 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7468 if (ShiftOp && !ShiftOp->isShift())
7469 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007470
Reid Spencerb83eb642006-10-20 07:07:24 +00007471 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007472 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007473 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7474 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007475 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7476 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7477 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007478
Zhou Sheng4351c642007-04-02 08:20:41 +00007479 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007480
7481 const IntegerType *Ty = cast<IntegerType>(I.getType());
7482
7483 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007484 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007485 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7486 // saturates.
7487 if (AmtSum >= TypeBits) {
7488 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007489 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007490 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7491 }
7492
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007493 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007494 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007495 }
7496
7497 if (ShiftOp->getOpcode() == Instruction::LShr &&
7498 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007499 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007501
Chris Lattnerb87056f2007-02-05 00:57:54 +00007502 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007503 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007504 }
7505
7506 if (ShiftOp->getOpcode() == Instruction::AShr &&
7507 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007508 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007509 if (AmtSum >= TypeBits)
7510 AmtSum = TypeBits-1;
7511
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007512 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007513
Zhou Shenge9e03f62007-03-28 15:02:20 +00007514 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007515 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007516 }
7517
Chris Lattnerb87056f2007-02-05 00:57:54 +00007518 // Okay, if we get here, one shift must be left, and the other shift must be
7519 // right. See if the amounts are equal.
7520 if (ShiftAmt1 == ShiftAmt2) {
7521 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7522 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007523 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007524 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007525 }
7526 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7527 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007528 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007529 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007530 }
7531 // We can simplify ((X << C) >>s C) into a trunc + sext.
7532 // NOTE: we could do this for any C, but that would make 'unusual' integer
7533 // types. For now, just stick to ones well-supported by the code
7534 // generators.
7535 const Type *SExtType = 0;
7536 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007537 case 1 :
7538 case 8 :
7539 case 16 :
7540 case 32 :
7541 case 64 :
7542 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007543 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007544 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007545 default: break;
7546 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007547 if (SExtType)
7548 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007549 // Otherwise, we can't handle it yet.
7550 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007551 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007552
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007553 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007554 if (I.getOpcode() == Instruction::Shl) {
7555 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7556 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007557 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007558
Reid Spencer55702aa2007-03-25 21:11:44 +00007559 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007560 return BinaryOperator::CreateAnd(Shift,
7561 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007562 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007563
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007564 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007565 if (I.getOpcode() == Instruction::LShr) {
7566 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007567 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007568
Reid Spencerd5e30f02007-03-26 17:18:58 +00007569 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007570 return BinaryOperator::CreateAnd(Shift,
7571 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007572 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007573
7574 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7575 } else {
7576 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007577 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007578
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007579 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007580 if (I.getOpcode() == Instruction::Shl) {
7581 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7582 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007583 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7584 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007585
Reid Spencer55702aa2007-03-25 21:11:44 +00007586 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007587 return BinaryOperator::CreateAnd(Shift,
7588 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007589 }
7590
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007591 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007592 if (I.getOpcode() == Instruction::LShr) {
7593 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007594 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007595
Reid Spencer68d27cf2007-03-26 23:45:51 +00007596 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007597 return BinaryOperator::CreateAnd(Shift,
7598 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007599 }
7600
7601 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007602 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007603 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007604 return 0;
7605}
7606
Chris Lattnera1be5662002-05-02 17:06:02 +00007607
Chris Lattnercfd65102005-10-29 04:36:15 +00007608/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7609/// expression. If so, decompose it, returning some value X, such that Val is
7610/// X*Scale+Offset.
7611///
7612static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007613 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007614 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7615 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007616 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007617 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007618 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007619 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007620 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7621 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7622 if (I->getOpcode() == Instruction::Shl) {
7623 // This is a value scaled by '1 << the shift amt'.
7624 Scale = 1U << RHS->getZExtValue();
7625 Offset = 0;
7626 return I->getOperand(0);
7627 } else if (I->getOpcode() == Instruction::Mul) {
7628 // This value is scaled by 'RHS'.
7629 Scale = RHS->getZExtValue();
7630 Offset = 0;
7631 return I->getOperand(0);
7632 } else if (I->getOpcode() == Instruction::Add) {
7633 // We have X+C. Check to see if we really have (X*C2)+C1,
7634 // where C1 is divisible by C2.
7635 unsigned SubScale;
7636 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007637 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7638 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007639 Offset += RHS->getZExtValue();
7640 Scale = SubScale;
7641 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007642 }
7643 }
7644 }
7645
7646 // Otherwise, we can't look past this.
7647 Scale = 1;
7648 Offset = 0;
7649 return Val;
7650}
7651
7652
Chris Lattnerb3f83972005-10-24 06:03:58 +00007653/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7654/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007655Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007656 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007657 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007658
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007659 BuilderTy AllocaBuilder(*Builder);
7660 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7661
Chris Lattnerb53c2382005-10-24 06:22:12 +00007662 // Remove any uses of AI that are dead.
7663 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007664
Chris Lattnerb53c2382005-10-24 06:22:12 +00007665 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7666 Instruction *User = cast<Instruction>(*UI++);
7667 if (isInstructionTriviallyDead(User)) {
7668 while (UI != E && *UI == User)
7669 ++UI; // If this instruction uses AI more than once, don't break UI.
7670
Chris Lattnerb53c2382005-10-24 06:22:12 +00007671 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007672 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007673 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007674 }
7675 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007676
7677 // This requires TargetData to get the alloca alignment and size information.
7678 if (!TD) return 0;
7679
Chris Lattnerb3f83972005-10-24 06:03:58 +00007680 // Get the type really allocated and the type casted to.
7681 const Type *AllocElTy = AI.getAllocatedType();
7682 const Type *CastElTy = PTy->getElementType();
7683 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007684
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007685 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7686 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007687 if (CastElTyAlign < AllocElTyAlign) return 0;
7688
Chris Lattner39387a52005-10-24 06:35:18 +00007689 // If the allocation has multiple uses, only promote it if we are strictly
7690 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007691 // same, we open the door to infinite loops of various kinds. (A reference
7692 // from a dbg.declare doesn't count as a use for this purpose.)
7693 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7694 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007695
Duncan Sands777d2302009-05-09 07:06:46 +00007696 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7697 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007698 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007699
Chris Lattner455fcc82005-10-29 03:19:53 +00007700 // See if we can satisfy the modulus by pulling a scale out of the array
7701 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007702 unsigned ArraySizeScale;
7703 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007704 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007705 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7706 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007707
Chris Lattner455fcc82005-10-29 03:19:53 +00007708 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7709 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007710 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7711 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007712
Chris Lattner455fcc82005-10-29 03:19:53 +00007713 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7714 Value *Amt = 0;
7715 if (Scale == 1) {
7716 Amt = NumElements;
7717 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007718 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007719 // Insert before the alloca, not before the cast.
7720 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007721 }
7722
Jeff Cohen86796be2007-04-04 16:58:57 +00007723 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007724 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007725 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007726 }
7727
Chris Lattnerb3f83972005-10-24 06:03:58 +00007728 AllocationInst *New;
7729 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007730 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007731 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007732 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7733 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007734 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007735
Dale Johannesena0a66372009-03-05 00:39:02 +00007736 // If the allocation has one real use plus a dbg.declare, just remove the
7737 // declare.
7738 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7739 EraseInstFromFunction(*DI);
7740 }
7741 // If the allocation has multiple real uses, insert a cast and change all
7742 // things that used it to use the new cast. This will also hack on CI, but it
7743 // will die soon.
7744 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007745 // New is the allocation instruction, pointer typed. AI is the original
7746 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007747 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007748 AI.replaceAllUsesWith(NewCast);
7749 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007750 return ReplaceInstUsesWith(CI, New);
7751}
7752
Chris Lattner70074e02006-05-13 02:06:03 +00007753/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007754/// and return it as type Ty without inserting any new casts and without
7755/// changing the computed value. This is used by code that tries to decide
7756/// whether promoting or shrinking integer operations to wider or smaller types
7757/// will allow us to eliminate a truncate or extend.
7758///
7759/// This is a truncation operation if Ty is smaller than V->getType(), or an
7760/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007761///
7762/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7763/// should return true if trunc(V) can be computed by computing V in the smaller
7764/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7765/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7766/// efficiently truncated.
7767///
7768/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7769/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7770/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007771bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007772 unsigned CastOpc,
7773 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007774 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007775 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007776 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007777
7778 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007779 if (!I) return false;
7780
Dan Gohman6de29f82009-06-15 22:12:54 +00007781 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007782
Chris Lattner951626b2007-08-02 06:11:14 +00007783 // If this is an extension or truncate, we can often eliminate it.
7784 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7785 // If this is a cast from the destination type, we can trivially eliminate
7786 // it, and this will remove a cast overall.
7787 if (I->getOperand(0)->getType() == Ty) {
7788 // If the first operand is itself a cast, and is eliminable, do not count
7789 // this as an eliminable cast. We would prefer to eliminate those two
7790 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007791 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007792 ++NumCastsRemoved;
7793 return true;
7794 }
7795 }
7796
7797 // We can't extend or shrink something that has multiple uses: doing so would
7798 // require duplicating the instruction in general, which isn't profitable.
7799 if (!I->hasOneUse()) return false;
7800
Evan Chengf35fd542009-01-15 17:01:23 +00007801 unsigned Opc = I->getOpcode();
7802 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007803 case Instruction::Add:
7804 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007805 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007806 case Instruction::And:
7807 case Instruction::Or:
7808 case Instruction::Xor:
7809 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007810 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007811 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007812 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007813 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007814
Eli Friedman070a9812009-07-13 22:46:01 +00007815 case Instruction::UDiv:
7816 case Instruction::URem: {
7817 // UDiv and URem can be truncated if all the truncated bits are zero.
7818 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7819 uint32_t BitWidth = Ty->getScalarSizeInBits();
7820 if (BitWidth < OrigBitWidth) {
7821 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7822 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7823 MaskedValueIsZero(I->getOperand(1), Mask)) {
7824 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7825 NumCastsRemoved) &&
7826 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7827 NumCastsRemoved);
7828 }
7829 }
7830 break;
7831 }
Chris Lattner46b96052006-11-29 07:18:39 +00007832 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007833 // If we are truncating the result of this SHL, and if it's a shift of a
7834 // constant amount, we can always perform a SHL in a smaller type.
7835 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007836 uint32_t BitWidth = Ty->getScalarSizeInBits();
7837 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007838 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007839 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007840 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007841 }
7842 break;
7843 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007844 // If this is a truncate of a logical shr, we can truncate it to a smaller
7845 // lshr iff we know that the bits we would otherwise be shifting in are
7846 // already zeros.
7847 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007848 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7849 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007850 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007851 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007852 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7853 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007854 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007855 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007856 }
7857 }
Chris Lattner46b96052006-11-29 07:18:39 +00007858 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007859 case Instruction::ZExt:
7860 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007861 case Instruction::Trunc:
7862 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007863 // can safely replace it. Note that replacing it does not reduce the number
7864 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007865 if (Opc == CastOpc)
7866 return true;
7867
7868 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007869 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007870 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007871 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007872 case Instruction::Select: {
7873 SelectInst *SI = cast<SelectInst>(I);
7874 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007875 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007876 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007877 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007878 }
Chris Lattner8114b712008-06-18 04:00:49 +00007879 case Instruction::PHI: {
7880 // We can change a phi if we can change all operands.
7881 PHINode *PN = cast<PHINode>(I);
7882 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7883 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007884 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007885 return false;
7886 return true;
7887 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007888 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007889 // TODO: Can handle more cases here.
7890 break;
7891 }
7892
7893 return false;
7894}
7895
7896/// EvaluateInDifferentType - Given an expression that
7897/// CanEvaluateInDifferentType returns true for, actually insert the code to
7898/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007899Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007901 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007902 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007903 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007904
7905 // Otherwise, it must be an instruction.
7906 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007907 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007908 unsigned Opc = I->getOpcode();
7909 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007910 case Instruction::Add:
7911 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007912 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007913 case Instruction::And:
7914 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007915 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007916 case Instruction::AShr:
7917 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007918 case Instruction::Shl:
7919 case Instruction::UDiv:
7920 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007921 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007922 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007923 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007924 break;
7925 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007926 case Instruction::Trunc:
7927 case Instruction::ZExt:
7928 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007929 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007930 // just return the source. There's no need to insert it because it is not
7931 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007932 if (I->getOperand(0)->getType() == Ty)
7933 return I->getOperand(0);
7934
Chris Lattner8114b712008-06-18 04:00:49 +00007935 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007936 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007937 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007938 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007939 case Instruction::Select: {
7940 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7941 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7942 Res = SelectInst::Create(I->getOperand(0), True, False);
7943 break;
7944 }
Chris Lattner8114b712008-06-18 04:00:49 +00007945 case Instruction::PHI: {
7946 PHINode *OPN = cast<PHINode>(I);
7947 PHINode *NPN = PHINode::Create(Ty);
7948 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7949 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7950 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7951 }
7952 Res = NPN;
7953 break;
7954 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007955 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007956 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00007957 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00007958 break;
7959 }
7960
Chris Lattner8114b712008-06-18 04:00:49 +00007961 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007962 return InsertNewInstBefore(Res, *I);
7963}
7964
Reid Spencer3da59db2006-11-27 01:05:10 +00007965/// @brief Implement the transforms common to all CastInst visitors.
7966Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007967 Value *Src = CI.getOperand(0);
7968
Dan Gohman23d9d272007-05-11 21:10:54 +00007969 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007970 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007971 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007972 if (Instruction::CastOps opc =
7973 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7974 // The first cast (CSrc) is eliminable so we need to fix up or replace
7975 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007976 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007977 }
7978 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007979
Reid Spencer3da59db2006-11-27 01:05:10 +00007980 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007981 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7982 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7983 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007984
7985 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007986 if (isa<PHINode>(Src))
7987 if (Instruction *NV = FoldOpIntoPhi(CI))
7988 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007989
Reid Spencer3da59db2006-11-27 01:05:10 +00007990 return 0;
7991}
7992
Chris Lattner46cd5a12009-01-09 05:44:56 +00007993/// FindElementAtOffset - Given a type and a constant offset, determine whether
7994/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007995/// the specified offset. If so, fill them into NewIndices and return the
7996/// resultant element type, otherwise return null.
7997static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7998 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00007999 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008000 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008001 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008002 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008003
8004 // Start with the index over the outer type. Note that the type size
8005 // might be zero (even if the offset isn't zero) if the indexed type
8006 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008007 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008008 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008009 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008010 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008011 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008012
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008013 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008014 if (Offset < 0) {
8015 --FirstIdx;
8016 Offset += TySize;
8017 assert(Offset >= 0);
8018 }
8019 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8020 }
8021
Owen Andersoneed707b2009-07-24 23:12:02 +00008022 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008023
8024 // Index into the types. If we fail, set OrigBase to null.
8025 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008026 // Indexing into tail padding between struct/array elements.
8027 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008028 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008029
Chris Lattner46cd5a12009-01-09 05:44:56 +00008030 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8031 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008032 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8033 "Offset must stay within the indexed type");
8034
Chris Lattner46cd5a12009-01-09 05:44:56 +00008035 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008036 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008037
8038 Offset -= SL->getElementOffset(Elt);
8039 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008040 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008041 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008042 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008043 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008044 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008045 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008046 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008047 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008048 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008049 }
8050 }
8051
Chris Lattner3914f722009-01-24 01:00:13 +00008052 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008053}
8054
Chris Lattnerd3e28342007-04-27 17:44:50 +00008055/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8056Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8057 Value *Src = CI.getOperand(0);
8058
Chris Lattnerd3e28342007-04-27 17:44:50 +00008059 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008060 // If casting the result of a getelementptr instruction with no offset, turn
8061 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008062 if (GEP->hasAllZeroIndices()) {
8063 // Changing the cast operand is usually not a good idea but it is safe
8064 // here because the pointer operand is being replaced with another
8065 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008066 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008067 CI.setOperand(0, GEP->getOperand(0));
8068 return &CI;
8069 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008070
8071 // If the GEP has a single use, and the base pointer is a bitcast, and the
8072 // GEP computes a constant offset, see if we can convert these three
8073 // instructions into fewer. This typically happens with unions and other
8074 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008075 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008076 if (GEP->hasAllConstantIndices()) {
8077 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008078 ConstantInt *OffsetV =
8079 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008080 int64_t Offset = OffsetV->getSExtValue();
8081
8082 // Get the base pointer input of the bitcast, and the type it points to.
8083 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8084 const Type *GEPIdxTy =
8085 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008086 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008087 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008088 // If we were able to index down into an element, create the GEP
8089 // and bitcast the result. This eliminates one bitcast, potentially
8090 // two.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008091 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8092 NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008093 NGEP->takeName(GEP);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008094 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008095 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008096
Chris Lattner46cd5a12009-01-09 05:44:56 +00008097 if (isa<BitCastInst>(CI))
8098 return new BitCastInst(NGEP, CI.getType());
8099 assert(isa<PtrToIntInst>(CI));
8100 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008101 }
8102 }
8103 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008104 }
8105
8106 return commonCastTransforms(CI);
8107}
8108
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008109/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8110/// type like i42. We don't want to introduce operations on random non-legal
8111/// integer types where they don't already exist in the code. In the future,
8112/// we should consider making this based off target-data, so that 32-bit targets
8113/// won't get i64 operations etc.
8114static bool isSafeIntegerType(const Type *Ty) {
8115 switch (Ty->getPrimitiveSizeInBits()) {
8116 case 8:
8117 case 16:
8118 case 32:
8119 case 64:
8120 return true;
8121 default:
8122 return false;
8123 }
8124}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008125
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008126/// commonIntCastTransforms - This function implements the common transforms
8127/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008128Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8129 if (Instruction *Result = commonCastTransforms(CI))
8130 return Result;
8131
8132 Value *Src = CI.getOperand(0);
8133 const Type *SrcTy = Src->getType();
8134 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008135 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8136 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008137
Reid Spencer3da59db2006-11-27 01:05:10 +00008138 // See if we can simplify any instructions used by the LHS whose sole
8139 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008140 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008141 return &CI;
8142
8143 // If the source isn't an instruction or has more than one use then we
8144 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008145 Instruction *SrcI = dyn_cast<Instruction>(Src);
8146 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008147 return 0;
8148
Chris Lattnerc739cd62007-03-03 05:27:34 +00008149 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008150 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008151 // Only do this if the dest type is a simple type, don't convert the
8152 // expression tree to something weird like i93 unless the source is also
8153 // strange.
8154 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008155 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8156 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008157 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008158 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008159 // eliminates the cast, so it is always a win. If this is a zero-extension,
8160 // we need to do an AND to maintain the clear top-part of the computation,
8161 // so we require that the input have eliminated at least one cast. If this
8162 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008163 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008164 bool DoXForm = false;
8165 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008166 switch (CI.getOpcode()) {
8167 default:
8168 // All the others use floating point so we shouldn't actually
8169 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008170 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008171 case Instruction::Trunc:
8172 DoXForm = true;
8173 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008174 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008175 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008176 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008177 // If it's unnecessary to issue an AND to clear the high bits, it's
8178 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008179 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008180 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8181 if (MaskedValueIsZero(TryRes, Mask))
8182 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008183
8184 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008185 if (TryI->use_empty())
8186 EraseInstFromFunction(*TryI);
8187 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008188 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008189 }
Evan Chengf35fd542009-01-15 17:01:23 +00008190 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008191 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008192 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008193 // If we do not have to emit the truncate + sext pair, then it's always
8194 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008195 //
8196 // It's not safe to eliminate the trunc + sext pair if one of the
8197 // eliminated cast is a truncate. e.g.
8198 // t2 = trunc i32 t1 to i16
8199 // t3 = sext i16 t2 to i32
8200 // !=
8201 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008202 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008203 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8204 if (NumSignBits > (DestBitSize - SrcBitSize))
8205 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008206
8207 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008208 if (TryI->use_empty())
8209 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008210 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008211 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008212 }
Evan Chengf35fd542009-01-15 17:01:23 +00008213 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008214
8215 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008216 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8217 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008218 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8219 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008220 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008221 // Just replace this cast with the result.
8222 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008223
Reid Spencer3da59db2006-11-27 01:05:10 +00008224 assert(Res->getType() == DestTy);
8225 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008226 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008227 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008228 // Just replace this cast with the result.
8229 return ReplaceInstUsesWith(CI, Res);
8230 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008231 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008232
8233 // If the high bits are already zero, just replace this cast with the
8234 // result.
8235 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8236 if (MaskedValueIsZero(Res, Mask))
8237 return ReplaceInstUsesWith(CI, Res);
8238
8239 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008240 Constant *C = ConstantInt::get(*Context,
8241 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008242 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008243 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008244 case Instruction::SExt: {
8245 // If the high bits are already filled with sign bit, just replace this
8246 // cast with the result.
8247 unsigned NumSignBits = ComputeNumSignBits(Res);
8248 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008249 return ReplaceInstUsesWith(CI, Res);
8250
Reid Spencer3da59db2006-11-27 01:05:10 +00008251 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008252 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008253 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008254 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008255 }
8256 }
8257
8258 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8259 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8260
8261 switch (SrcI->getOpcode()) {
8262 case Instruction::Add:
8263 case Instruction::Mul:
8264 case Instruction::And:
8265 case Instruction::Or:
8266 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008267 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008268 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8269 // Don't insert two casts unless at least one can be eliminated.
8270 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008271 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008272 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8273 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008274 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008275 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 }
8277 }
8278
8279 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8280 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8281 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008282 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008283 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008284 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008285 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008286 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008287 }
8288 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008289
Eli Friedman65445c52009-07-13 21:45:57 +00008290 case Instruction::Shl: {
8291 // Canonicalize trunc inside shl, if we can.
8292 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8293 if (CI && DestBitSize < SrcBitSize &&
8294 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008295 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8296 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008297 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008298 }
8299 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008300 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008301 }
8302 return 0;
8303}
8304
Chris Lattner8a9f5712007-04-11 06:57:46 +00008305Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008306 if (Instruction *Result = commonIntCastTransforms(CI))
8307 return Result;
8308
8309 Value *Src = CI.getOperand(0);
8310 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008311 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8312 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008313
8314 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008315 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008316 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008317 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008318 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008319 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008320 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008321
Chris Lattner4f9797d2009-03-24 18:15:30 +00008322 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8323 ConstantInt *ShAmtV = 0;
8324 Value *ShiftOp = 0;
8325 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008326 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008327 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8328
8329 // Get a mask for the bits shifting in.
8330 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8331 if (MaskedValueIsZero(ShiftOp, Mask)) {
8332 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008333 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008334
8335 // Okay, we can shrink this. Truncate the input, then return a new
8336 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008337 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008338 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008339 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008340 }
8341 }
8342
8343 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008344}
8345
Evan Chengb98a10e2008-03-24 00:21:34 +00008346/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8347/// in order to eliminate the icmp.
8348Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8349 bool DoXform) {
8350 // If we are just checking for a icmp eq of a single bit and zext'ing it
8351 // to an integer, then shift the bit to the appropriate place and then
8352 // cast to integer to avoid the comparison.
8353 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8354 const APInt &Op1CV = Op1C->getValue();
8355
8356 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8357 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8358 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8359 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8360 if (!DoXform) return ICI;
8361
8362 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008363 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008364 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008365 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008366 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008367 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008368
8369 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008370 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008371 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008372 }
8373
8374 return ReplaceInstUsesWith(CI, In);
8375 }
8376
8377
8378
8379 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8380 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8381 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8382 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8383 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8384 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8385 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8386 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8387 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8388 // This only works for EQ and NE
8389 ICI->isEquality()) {
8390 // If Op1C some other power of two, convert:
8391 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8392 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8393 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8394 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8395
8396 APInt KnownZeroMask(~KnownZero);
8397 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8398 if (!DoXform) return ICI;
8399
8400 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8401 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8402 // (X&4) == 2 --> false
8403 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008404 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008405 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008406 return ReplaceInstUsesWith(CI, Res);
8407 }
8408
8409 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8410 Value *In = ICI->getOperand(0);
8411 if (ShiftAmt) {
8412 // Perform a logical shr by shiftamt.
8413 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008414 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8415 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008416 }
8417
8418 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008419 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008420 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008421 }
8422
8423 if (CI.getType() == In->getType())
8424 return ReplaceInstUsesWith(CI, In);
8425 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008426 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008427 }
8428 }
8429 }
8430
8431 return 0;
8432}
8433
Chris Lattner8a9f5712007-04-11 06:57:46 +00008434Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008435 // If one of the common conversion will work ..
8436 if (Instruction *Result = commonIntCastTransforms(CI))
8437 return Result;
8438
8439 Value *Src = CI.getOperand(0);
8440
Chris Lattnera84f47c2009-02-17 20:47:23 +00008441 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8442 // types and if the sizes are just right we can convert this into a logical
8443 // 'and' which will be much cheaper than the pair of casts.
8444 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8445 // Get the sizes of the types involved. We know that the intermediate type
8446 // will be smaller than A or C, but don't know the relation between A and C.
8447 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008448 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8449 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8450 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008451 // If we're actually extending zero bits, then if
8452 // SrcSize < DstSize: zext(a & mask)
8453 // SrcSize == DstSize: a & mask
8454 // SrcSize > DstSize: trunc(a) & mask
8455 if (SrcSize < DstSize) {
8456 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008457 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008458 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008459 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008460 }
8461
8462 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008463 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008464 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008465 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008466 }
8467 if (SrcSize > DstSize) {
8468 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008469 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008470 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008471 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008472 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008473 }
8474 }
8475
Evan Chengb98a10e2008-03-24 00:21:34 +00008476 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8477 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008478
Evan Chengb98a10e2008-03-24 00:21:34 +00008479 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8480 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8481 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8482 // of the (zext icmp) will be transformed.
8483 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8484 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8485 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8486 (transformZExtICmp(LHS, CI, false) ||
8487 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008488 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8489 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008490 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008491 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008492 }
8493
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008494 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008495 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8496 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8497 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8498 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008499 if (TI0->getType() == CI.getType())
8500 return
8501 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008502 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008503 }
8504
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008505 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8506 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8507 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8508 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8509 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8510 And->getOperand(1) == C)
8511 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8512 Value *TI0 = TI->getOperand(0);
8513 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008514 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008515 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008516 return BinaryOperator::CreateXor(NewAnd, ZC);
8517 }
8518 }
8519
Reid Spencer3da59db2006-11-27 01:05:10 +00008520 return 0;
8521}
8522
Chris Lattner8a9f5712007-04-11 06:57:46 +00008523Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008524 if (Instruction *I = commonIntCastTransforms(CI))
8525 return I;
8526
Chris Lattner8a9f5712007-04-11 06:57:46 +00008527 Value *Src = CI.getOperand(0);
8528
Dan Gohman1975d032008-10-30 20:40:10 +00008529 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008530 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008531 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008532 Constant::getAllOnesValue(CI.getType()),
8533 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008534
8535 // See if the value being truncated is already sign extended. If so, just
8536 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008537 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008538 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008539 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8540 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8541 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008542 unsigned NumSignBits = ComputeNumSignBits(Op);
8543
8544 if (OpBits == DestBits) {
8545 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8546 // bits, it is already ready.
8547 if (NumSignBits > DestBits-MidBits)
8548 return ReplaceInstUsesWith(CI, Op);
8549 } else if (OpBits < DestBits) {
8550 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8551 // bits, just sext from i32.
8552 if (NumSignBits > OpBits-MidBits)
8553 return new SExtInst(Op, CI.getType(), "tmp");
8554 } else {
8555 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8556 // bits, just truncate to i32.
8557 if (NumSignBits > OpBits-MidBits)
8558 return new TruncInst(Op, CI.getType(), "tmp");
8559 }
8560 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008561
8562 // If the input is a shl/ashr pair of a same constant, then this is a sign
8563 // extension from a smaller value. If we could trust arbitrary bitwidth
8564 // integers, we could turn this into a truncate to the smaller bit and then
8565 // use a sext for the whole extension. Since we don't, look deeper and check
8566 // for a truncate. If the source and dest are the same type, eliminate the
8567 // trunc and extend and just do shifts. For example, turn:
8568 // %a = trunc i32 %i to i8
8569 // %b = shl i8 %a, 6
8570 // %c = ashr i8 %b, 6
8571 // %d = sext i8 %c to i32
8572 // into:
8573 // %a = shl i32 %i, 30
8574 // %d = ashr i32 %a, 30
8575 Value *A = 0;
8576 ConstantInt *BA = 0, *CA = 0;
8577 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008578 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008579 BA == CA && isa<TruncInst>(A)) {
8580 Value *I = cast<TruncInst>(A)->getOperand(0);
8581 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008582 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8583 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008584 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008585 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008586 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008587 return BinaryOperator::CreateAShr(I, ShAmtV);
8588 }
8589 }
8590
Chris Lattnerba417832007-04-11 06:12:58 +00008591 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008592}
8593
Chris Lattnerb7530652008-01-27 05:29:54 +00008594/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8595/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008596static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008597 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008598 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008599 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008600 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8601 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008602 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008603 return 0;
8604}
8605
8606/// LookThroughFPExtensions - If this is an fp extension instruction, look
8607/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008608static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008609 if (Instruction *I = dyn_cast<Instruction>(V))
8610 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008611 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008612
8613 // If this value is a constant, return the constant in the smallest FP type
8614 // that can accurately represent it. This allows us to turn
8615 // (float)((double)X+2.0) into x+2.0f.
8616 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008617 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008618 return V; // No constant folding of this.
8619 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008620 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008621 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008622 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008623 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008624 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008625 return V;
8626 // Don't try to shrink to various long double types.
8627 }
8628
8629 return V;
8630}
8631
8632Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8633 if (Instruction *I = commonCastTransforms(CI))
8634 return I;
8635
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008636 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008637 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008638 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008639 // many builtins (sqrt, etc).
8640 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8641 if (OpI && OpI->hasOneUse()) {
8642 switch (OpI->getOpcode()) {
8643 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008644 case Instruction::FAdd:
8645 case Instruction::FSub:
8646 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008647 case Instruction::FDiv:
8648 case Instruction::FRem:
8649 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008650 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8651 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008652 if (LHSTrunc->getType() != SrcTy &&
8653 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008654 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008655 // If the source types were both smaller than the destination type of
8656 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008657 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8658 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008659 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8660 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008661 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008662 }
8663 }
8664 break;
8665 }
8666 }
8667 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008668}
8669
8670Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8671 return commonCastTransforms(CI);
8672}
8673
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008674Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008675 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8676 if (OpI == 0)
8677 return commonCastTransforms(FI);
8678
8679 // fptoui(uitofp(X)) --> X
8680 // fptoui(sitofp(X)) --> X
8681 // This is safe if the intermediate type has enough bits in its mantissa to
8682 // accurately represent all values of X. For example, do not do this with
8683 // i64->float->i64. This is also safe for sitofp case, because any negative
8684 // 'X' value would cause an undefined result for the fptoui.
8685 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8686 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008687 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008688 OpI->getType()->getFPMantissaWidth())
8689 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008690
8691 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008692}
8693
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008694Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008695 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8696 if (OpI == 0)
8697 return commonCastTransforms(FI);
8698
8699 // fptosi(sitofp(X)) --> X
8700 // fptosi(uitofp(X)) --> X
8701 // This is safe if the intermediate type has enough bits in its mantissa to
8702 // accurately represent all values of X. For example, do not do this with
8703 // i64->float->i64. This is also safe for sitofp case, because any negative
8704 // 'X' value would cause an undefined result for the fptoui.
8705 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8706 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008707 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008708 OpI->getType()->getFPMantissaWidth())
8709 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008710
8711 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008712}
8713
8714Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8715 return commonCastTransforms(CI);
8716}
8717
8718Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8719 return commonCastTransforms(CI);
8720}
8721
Chris Lattnera0e69692009-03-24 18:35:40 +00008722Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8723 // If the destination integer type is smaller than the intptr_t type for
8724 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8725 // trunc to be exposed to other transforms. Don't do this for extending
8726 // ptrtoint's, because we don't know if the target sign or zero extends its
8727 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008728 if (TD &&
8729 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008730 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8731 TD->getIntPtrType(CI.getContext()),
8732 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008733 return new TruncInst(P, CI.getType());
8734 }
8735
Chris Lattnerd3e28342007-04-27 17:44:50 +00008736 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008737}
8738
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008739Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008740 // If the source integer type is larger than the intptr_t type for
8741 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8742 // allows the trunc to be exposed to other transforms. Don't do this for
8743 // extending inttoptr's, because we don't know if the target sign or zero
8744 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008745 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008746 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008747 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8748 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008749 return new IntToPtrInst(P, CI.getType());
8750 }
8751
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008752 if (Instruction *I = commonCastTransforms(CI))
8753 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008754
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008755 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008756}
8757
Chris Lattnerd3e28342007-04-27 17:44:50 +00008758Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008759 // If the operands are integer typed then apply the integer transforms,
8760 // otherwise just apply the common ones.
8761 Value *Src = CI.getOperand(0);
8762 const Type *SrcTy = Src->getType();
8763 const Type *DestTy = CI.getType();
8764
Eli Friedman7e25d452009-07-13 20:53:00 +00008765 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008766 if (Instruction *I = commonPointerCastTransforms(CI))
8767 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008768 } else {
8769 if (Instruction *Result = commonCastTransforms(CI))
8770 return Result;
8771 }
8772
8773
8774 // Get rid of casts from one type to the same type. These are useless and can
8775 // be replaced by the operand.
8776 if (DestTy == Src->getType())
8777 return ReplaceInstUsesWith(CI, Src);
8778
Reid Spencer3da59db2006-11-27 01:05:10 +00008779 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008780 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8781 const Type *DstElTy = DstPTy->getElementType();
8782 const Type *SrcElTy = SrcPTy->getElementType();
8783
Nate Begeman83ad90a2008-03-31 00:22:16 +00008784 // If the address spaces don't match, don't eliminate the bitcast, which is
8785 // required for changing types.
8786 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8787 return 0;
8788
Chris Lattnerd3e28342007-04-27 17:44:50 +00008789 // If we are casting a malloc or alloca to a pointer to a type of the same
8790 // size, rewrite the allocation instruction to allocate the "right" type.
8791 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8792 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8793 return V;
8794
Chris Lattnerd717c182007-05-05 22:32:24 +00008795 // If the source and destination are pointers, and this cast is equivalent
8796 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008797 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008798 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008799 unsigned NumZeros = 0;
8800 while (SrcElTy != DstElTy &&
8801 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8802 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8803 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8804 ++NumZeros;
8805 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008806
Chris Lattnerd3e28342007-04-27 17:44:50 +00008807 // If we found a path from the src to dest, create the getelementptr now.
8808 if (SrcElTy == DstElTy) {
8809 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008810 Instruction *GEP = GetElementPtrInst::Create(Src,
8811 Idxs.begin(), Idxs.end(), "",
8812 ((Instruction*) NULL));
8813 cast<GEPOperator>(GEP)->setIsInBounds(true);
8814 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008815 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008816 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008817
Eli Friedman2451a642009-07-18 23:06:53 +00008818 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8819 if (DestVTy->getNumElements() == 1) {
8820 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008821 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008822 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008823 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008824 }
8825 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8826 }
8827 }
8828
8829 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8830 if (SrcVTy->getNumElements() == 1) {
8831 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008832 Value *Elem =
8833 Builder->CreateExtractElement(Src,
8834 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008835 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8836 }
8837 }
8838 }
8839
Reid Spencer3da59db2006-11-27 01:05:10 +00008840 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8841 if (SVI->hasOneUse()) {
8842 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8843 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008844 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008845 cast<VectorType>(DestTy)->getNumElements() ==
8846 SVI->getType()->getNumElements() &&
8847 SVI->getType()->getNumElements() ==
8848 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008849 CastInst *Tmp;
8850 // If either of the operands is a cast from CI.getType(), then
8851 // evaluating the shuffle in the casted destination's type will allow
8852 // us to eliminate at least one cast.
8853 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8854 Tmp->getOperand(0)->getType() == DestTy) ||
8855 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8856 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008857 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8858 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008859 // Return a new shuffle vector. Use the same element ID's, as we
8860 // know the vector types match #elts.
8861 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008862 }
8863 }
8864 }
8865 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008866 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008867}
8868
Chris Lattnere576b912004-04-09 23:46:01 +00008869/// GetSelectFoldableOperands - We want to turn code that looks like this:
8870/// %C = or %A, %B
8871/// %D = select %cond, %C, %A
8872/// into:
8873/// %C = select %cond, %B, 0
8874/// %D = or %A, %C
8875///
8876/// Assuming that the specified instruction is an operand to the select, return
8877/// a bitmask indicating which operands of this instruction are foldable if they
8878/// equal the other incoming value of the select.
8879///
8880static unsigned GetSelectFoldableOperands(Instruction *I) {
8881 switch (I->getOpcode()) {
8882 case Instruction::Add:
8883 case Instruction::Mul:
8884 case Instruction::And:
8885 case Instruction::Or:
8886 case Instruction::Xor:
8887 return 3; // Can fold through either operand.
8888 case Instruction::Sub: // Can only fold on the amount subtracted.
8889 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008890 case Instruction::LShr:
8891 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008892 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008893 default:
8894 return 0; // Cannot fold
8895 }
8896}
8897
8898/// GetSelectFoldableConstant - For the same transformation as the previous
8899/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008900static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008901 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008902 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008903 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008904 case Instruction::Add:
8905 case Instruction::Sub:
8906 case Instruction::Or:
8907 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008908 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008909 case Instruction::LShr:
8910 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008911 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008912 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008913 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008914 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008915 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008916 }
8917}
8918
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008919/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8920/// have the same opcode and only one use each. Try to simplify this.
8921Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8922 Instruction *FI) {
8923 if (TI->getNumOperands() == 1) {
8924 // If this is a non-volatile load or a cast from the same type,
8925 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008926 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008927 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8928 return 0;
8929 } else {
8930 return 0; // unknown unary op.
8931 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008932
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008933 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008934 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008935 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008936 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008937 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008938 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008939 }
8940
Reid Spencer832254e2007-02-02 02:16:23 +00008941 // Only handle binary operators here.
8942 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008943 return 0;
8944
8945 // Figure out if the operations have any operands in common.
8946 Value *MatchOp, *OtherOpT, *OtherOpF;
8947 bool MatchIsOpZero;
8948 if (TI->getOperand(0) == FI->getOperand(0)) {
8949 MatchOp = TI->getOperand(0);
8950 OtherOpT = TI->getOperand(1);
8951 OtherOpF = FI->getOperand(1);
8952 MatchIsOpZero = true;
8953 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8954 MatchOp = TI->getOperand(1);
8955 OtherOpT = TI->getOperand(0);
8956 OtherOpF = FI->getOperand(0);
8957 MatchIsOpZero = false;
8958 } else if (!TI->isCommutative()) {
8959 return 0;
8960 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8961 MatchOp = TI->getOperand(0);
8962 OtherOpT = TI->getOperand(1);
8963 OtherOpF = FI->getOperand(0);
8964 MatchIsOpZero = true;
8965 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8966 MatchOp = TI->getOperand(1);
8967 OtherOpT = TI->getOperand(0);
8968 OtherOpF = FI->getOperand(1);
8969 MatchIsOpZero = true;
8970 } else {
8971 return 0;
8972 }
8973
8974 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008975 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8976 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008977 InsertNewInstBefore(NewSI, SI);
8978
8979 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8980 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008981 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008982 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008983 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008984 }
Torok Edwinc23197a2009-07-14 16:55:14 +00008985 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00008986 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008987}
8988
Evan Chengde621922009-03-31 20:42:45 +00008989static bool isSelect01(Constant *C1, Constant *C2) {
8990 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8991 if (!C1I)
8992 return false;
8993 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8994 if (!C2I)
8995 return false;
8996 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8997}
8998
8999/// FoldSelectIntoOp - Try fold the select into one of the operands to
9000/// facilitate further optimization.
9001Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9002 Value *FalseVal) {
9003 // See the comment above GetSelectFoldableOperands for a description of the
9004 // transformation we are doing here.
9005 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9006 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9007 !isa<Constant>(FalseVal)) {
9008 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9009 unsigned OpToFold = 0;
9010 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9011 OpToFold = 1;
9012 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9013 OpToFold = 2;
9014 }
9015
9016 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009017 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009018 Value *OOp = TVI->getOperand(2-OpToFold);
9019 // Avoid creating select between 2 constants unless it's selecting
9020 // between 0 and 1.
9021 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9022 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9023 InsertNewInstBefore(NewSel, SI);
9024 NewSel->takeName(TVI);
9025 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9026 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009027 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009028 }
9029 }
9030 }
9031 }
9032 }
9033
9034 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9035 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9036 !isa<Constant>(TrueVal)) {
9037 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9038 unsigned OpToFold = 0;
9039 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9040 OpToFold = 1;
9041 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9042 OpToFold = 2;
9043 }
9044
9045 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009046 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009047 Value *OOp = FVI->getOperand(2-OpToFold);
9048 // Avoid creating select between 2 constants unless it's selecting
9049 // between 0 and 1.
9050 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9051 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9052 InsertNewInstBefore(NewSel, SI);
9053 NewSel->takeName(FVI);
9054 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9055 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009056 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009057 }
9058 }
9059 }
9060 }
9061 }
9062
9063 return 0;
9064}
9065
Dan Gohman81b28ce2008-09-16 18:46:06 +00009066/// visitSelectInstWithICmp - Visit a SelectInst that has an
9067/// ICmpInst as its first operand.
9068///
9069Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9070 ICmpInst *ICI) {
9071 bool Changed = false;
9072 ICmpInst::Predicate Pred = ICI->getPredicate();
9073 Value *CmpLHS = ICI->getOperand(0);
9074 Value *CmpRHS = ICI->getOperand(1);
9075 Value *TrueVal = SI.getTrueValue();
9076 Value *FalseVal = SI.getFalseValue();
9077
9078 // Check cases where the comparison is with a constant that
9079 // can be adjusted to fit the min/max idiom. We may edit ICI in
9080 // place here, so make sure the select is the only user.
9081 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009082 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009083 switch (Pred) {
9084 default: break;
9085 case ICmpInst::ICMP_ULT:
9086 case ICmpInst::ICMP_SLT: {
9087 // X < MIN ? T : F --> F
9088 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9089 return ReplaceInstUsesWith(SI, FalseVal);
9090 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009091 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009092 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9093 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9094 Pred = ICmpInst::getSwappedPredicate(Pred);
9095 CmpRHS = AdjustedRHS;
9096 std::swap(FalseVal, TrueVal);
9097 ICI->setPredicate(Pred);
9098 ICI->setOperand(1, CmpRHS);
9099 SI.setOperand(1, TrueVal);
9100 SI.setOperand(2, FalseVal);
9101 Changed = true;
9102 }
9103 break;
9104 }
9105 case ICmpInst::ICMP_UGT:
9106 case ICmpInst::ICMP_SGT: {
9107 // X > MAX ? T : F --> F
9108 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9109 return ReplaceInstUsesWith(SI, FalseVal);
9110 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009111 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009112 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9113 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9114 Pred = ICmpInst::getSwappedPredicate(Pred);
9115 CmpRHS = AdjustedRHS;
9116 std::swap(FalseVal, TrueVal);
9117 ICI->setPredicate(Pred);
9118 ICI->setOperand(1, CmpRHS);
9119 SI.setOperand(1, TrueVal);
9120 SI.setOperand(2, FalseVal);
9121 Changed = true;
9122 }
9123 break;
9124 }
9125 }
9126
Dan Gohman1975d032008-10-30 20:40:10 +00009127 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9128 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009129 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009130 if (match(TrueVal, m_ConstantInt<-1>()) &&
9131 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009132 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009133 else if (match(TrueVal, m_ConstantInt<0>()) &&
9134 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009135 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9136
Dan Gohman1975d032008-10-30 20:40:10 +00009137 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9138 // If we are just checking for a icmp eq of a single bit and zext'ing it
9139 // to an integer, then shift the bit to the appropriate place and then
9140 // cast to integer to avoid the comparison.
9141 const APInt &Op1CV = CI->getValue();
9142
9143 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9144 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9145 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009146 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009147 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009148 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009149 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009150 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009151 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009152 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009153 if (In->getType() != SI.getType())
9154 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009155 true/*SExt*/, "tmp", ICI);
9156
9157 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009158 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009159 In->getName()+".not"), *ICI);
9160
9161 return ReplaceInstUsesWith(SI, In);
9162 }
9163 }
9164 }
9165
Dan Gohman81b28ce2008-09-16 18:46:06 +00009166 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9167 // Transform (X == Y) ? X : Y -> Y
9168 if (Pred == ICmpInst::ICMP_EQ)
9169 return ReplaceInstUsesWith(SI, FalseVal);
9170 // Transform (X != Y) ? X : Y -> X
9171 if (Pred == ICmpInst::ICMP_NE)
9172 return ReplaceInstUsesWith(SI, TrueVal);
9173 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9174
9175 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9176 // Transform (X == Y) ? Y : X -> X
9177 if (Pred == ICmpInst::ICMP_EQ)
9178 return ReplaceInstUsesWith(SI, FalseVal);
9179 // Transform (X != Y) ? Y : X -> Y
9180 if (Pred == ICmpInst::ICMP_NE)
9181 return ReplaceInstUsesWith(SI, TrueVal);
9182 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9183 }
9184
9185 /// NOTE: if we wanted to, this is where to detect integer ABS
9186
9187 return Changed ? &SI : 0;
9188}
9189
Chris Lattner3d69f462004-03-12 05:52:32 +00009190Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009191 Value *CondVal = SI.getCondition();
9192 Value *TrueVal = SI.getTrueValue();
9193 Value *FalseVal = SI.getFalseValue();
9194
9195 // select true, X, Y -> X
9196 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009197 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009198 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009199
9200 // select C, X, X -> X
9201 if (TrueVal == FalseVal)
9202 return ReplaceInstUsesWith(SI, TrueVal);
9203
Chris Lattnere87597f2004-10-16 18:11:37 +00009204 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9205 return ReplaceInstUsesWith(SI, FalseVal);
9206 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9207 return ReplaceInstUsesWith(SI, TrueVal);
9208 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9209 if (isa<Constant>(TrueVal))
9210 return ReplaceInstUsesWith(SI, TrueVal);
9211 else
9212 return ReplaceInstUsesWith(SI, FalseVal);
9213 }
9214
Owen Anderson1d0be152009-08-13 21:58:54 +00009215 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009216 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009217 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009218 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009219 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009220 } else {
9221 // Change: A = select B, false, C --> A = and !B, C
9222 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009223 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009224 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009225 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009226 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009227 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009228 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009229 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009230 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009231 } else {
9232 // Change: A = select B, C, true --> A = or !B, C
9233 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009234 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009235 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009236 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009237 }
9238 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009239
9240 // select a, b, a -> a&b
9241 // select a, a, b -> a|b
9242 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009243 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009244 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009245 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009246 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009247
Chris Lattner2eefe512004-04-09 19:05:30 +00009248 // Selecting between two integer constants?
9249 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9250 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009251 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009252 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009253 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009254 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009255 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009256 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009257 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009258 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009259 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009260 }
Chris Lattner457dd822004-06-09 07:59:58 +00009261
Reid Spencere4d87aa2006-12-23 06:05:41 +00009262 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009263 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009264 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009265 // non-constant value, eliminate this whole mess. This corresponds to
9266 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009267 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009268 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009269 cast<Constant>(IC->getOperand(1))->isNullValue())
9270 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9271 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009272 isa<ConstantInt>(ICA->getOperand(1)) &&
9273 (ICA->getOperand(1) == TrueValC ||
9274 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009275 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9276 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009277 // know whether we have a icmp_ne or icmp_eq and whether the
9278 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009279 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009280 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009281 Value *V = ICA;
9282 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009283 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009284 Instruction::Xor, V, ICA->getOperand(1)), SI);
9285 return ReplaceInstUsesWith(SI, V);
9286 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009287 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009288 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009289
9290 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009291 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9292 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009293 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009294 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9295 // This is not safe in general for floating point:
9296 // consider X== -0, Y== +0.
9297 // It becomes safe if either operand is a nonzero constant.
9298 ConstantFP *CFPt, *CFPf;
9299 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9300 !CFPt->getValueAPF().isZero()) ||
9301 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9302 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009303 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009304 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009305 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009306 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009307 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009308 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009309
Reid Spencere4d87aa2006-12-23 06:05:41 +00009310 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009311 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009312 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9313 // This is not safe in general for floating point:
9314 // consider X== -0, Y== +0.
9315 // It becomes safe if either operand is a nonzero constant.
9316 ConstantFP *CFPt, *CFPf;
9317 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9318 !CFPt->getValueAPF().isZero()) ||
9319 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9320 !CFPf->getValueAPF().isZero()))
9321 return ReplaceInstUsesWith(SI, FalseVal);
9322 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009323 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009324 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9325 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009326 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009327 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009328 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009329 }
9330
9331 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009332 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9333 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9334 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009335
Chris Lattner87875da2005-01-13 22:52:24 +00009336 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9337 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9338 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009339 Instruction *AddOp = 0, *SubOp = 0;
9340
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009341 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9342 if (TI->getOpcode() == FI->getOpcode())
9343 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9344 return IV;
9345
9346 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9347 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009348 if ((TI->getOpcode() == Instruction::Sub &&
9349 FI->getOpcode() == Instruction::Add) ||
9350 (TI->getOpcode() == Instruction::FSub &&
9351 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009352 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009353 } else if ((FI->getOpcode() == Instruction::Sub &&
9354 TI->getOpcode() == Instruction::Add) ||
9355 (FI->getOpcode() == Instruction::FSub &&
9356 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009357 AddOp = TI; SubOp = FI;
9358 }
9359
9360 if (AddOp) {
9361 Value *OtherAddOp = 0;
9362 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9363 OtherAddOp = AddOp->getOperand(1);
9364 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9365 OtherAddOp = AddOp->getOperand(0);
9366 }
9367
9368 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009369 // So at this point we know we have (Y -> OtherAddOp):
9370 // select C, (add X, Y), (sub X, Z)
9371 Value *NegVal; // Compute -Z
9372 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009373 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009374 } else {
9375 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009376 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009377 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009378 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009379
9380 Value *NewTrueOp = OtherAddOp;
9381 Value *NewFalseOp = NegVal;
9382 if (AddOp != TI)
9383 std::swap(NewTrueOp, NewFalseOp);
9384 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009385 SelectInst::Create(CondVal, NewTrueOp,
9386 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009387
9388 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009389 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009390 }
9391 }
9392 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009393
Chris Lattnere576b912004-04-09 23:46:01 +00009394 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009395 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009396 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9397 if (FoldI)
9398 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009399 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009400
9401 if (BinaryOperator::isNot(CondVal)) {
9402 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9403 SI.setOperand(1, FalseVal);
9404 SI.setOperand(2, TrueVal);
9405 return &SI;
9406 }
9407
Chris Lattner3d69f462004-03-12 05:52:32 +00009408 return 0;
9409}
9410
Dan Gohmaneee962e2008-04-10 18:43:06 +00009411/// EnforceKnownAlignment - If the specified pointer points to an object that
9412/// we control, modify the object's alignment to PrefAlign. This isn't
9413/// often possible though. If alignment is important, a more reliable approach
9414/// is to simply align all global variables and allocation instructions to
9415/// their preferred alignment from the beginning.
9416///
9417static unsigned EnforceKnownAlignment(Value *V,
9418 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009419
Dan Gohmaneee962e2008-04-10 18:43:06 +00009420 User *U = dyn_cast<User>(V);
9421 if (!U) return Align;
9422
Dan Gohmanca178902009-07-17 20:47:02 +00009423 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009424 default: break;
9425 case Instruction::BitCast:
9426 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9427 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009428 // If all indexes are zero, it is just the alignment of the base pointer.
9429 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009430 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009431 if (!isa<Constant>(*i) ||
9432 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009433 AllZeroOperands = false;
9434 break;
9435 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009436
9437 if (AllZeroOperands) {
9438 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009439 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009440 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009441 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009442 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009443 }
9444
9445 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9446 // If there is a large requested alignment and we can, bump up the alignment
9447 // of the global.
9448 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009449 if (GV->getAlignment() >= PrefAlign)
9450 Align = GV->getAlignment();
9451 else {
9452 GV->setAlignment(PrefAlign);
9453 Align = PrefAlign;
9454 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009455 }
9456 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9457 // If there is a requested alignment and if this is an alloca, round up. We
9458 // don't do this for malloc, because some systems can't respect the request.
9459 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009460 if (AI->getAlignment() >= PrefAlign)
9461 Align = AI->getAlignment();
9462 else {
9463 AI->setAlignment(PrefAlign);
9464 Align = PrefAlign;
9465 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009466 }
9467 }
9468
9469 return Align;
9470}
9471
9472/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9473/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9474/// and it is more than the alignment of the ultimate object, see if we can
9475/// increase the alignment of the ultimate object, making this check succeed.
9476unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9477 unsigned PrefAlign) {
9478 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9479 sizeof(PrefAlign) * CHAR_BIT;
9480 APInt Mask = APInt::getAllOnesValue(BitWidth);
9481 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9482 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9483 unsigned TrailZ = KnownZero.countTrailingOnes();
9484 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9485
9486 if (PrefAlign > Align)
9487 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9488
9489 // We don't need to make any adjustment.
9490 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009491}
9492
Chris Lattnerf497b022008-01-13 23:50:23 +00009493Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009494 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009495 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009496 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009497 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009498
9499 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009500 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009501 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009502 return MI;
9503 }
9504
9505 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9506 // load/store.
9507 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9508 if (MemOpLength == 0) return 0;
9509
Chris Lattner37ac6082008-01-14 00:28:35 +00009510 // Source and destination pointer types are always "i8*" for intrinsic. See
9511 // if the size is something we can handle with a single primitive load/store.
9512 // A single load+store correctly handles overlapping memory in the memmove
9513 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009514 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009515 if (Size == 0) return MI; // Delete this mem transfer.
9516
9517 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009518 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009519
Chris Lattner37ac6082008-01-14 00:28:35 +00009520 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009521 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009522 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009523
9524 // Memcpy forces the use of i8* for the source and destination. That means
9525 // that if you're using memcpy to move one double around, you'll get a cast
9526 // from double* to i8*. We'd much rather use a double load+store rather than
9527 // an i64 load+store, here because this improves the odds that the source or
9528 // dest address will be promotable. See if we can find a better type than the
9529 // integer datatype.
9530 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9531 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009532 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009533 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9534 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009535 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009536 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9537 if (STy->getNumElements() == 1)
9538 SrcETy = STy->getElementType(0);
9539 else
9540 break;
9541 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9542 if (ATy->getNumElements() == 1)
9543 SrcETy = ATy->getElementType();
9544 else
9545 break;
9546 } else
9547 break;
9548 }
9549
Dan Gohman8f8e2692008-05-23 01:52:21 +00009550 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009551 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009552 }
9553 }
9554
9555
Chris Lattnerf497b022008-01-13 23:50:23 +00009556 // If the memcpy/memmove provides better alignment info than we can
9557 // infer, use it.
9558 SrcAlign = std::max(SrcAlign, CopyAlign);
9559 DstAlign = std::max(DstAlign, CopyAlign);
9560
Chris Lattner08142f22009-08-30 19:47:22 +00009561 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9562 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009563 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9564 InsertNewInstBefore(L, *MI);
9565 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9566
9567 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009568 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009569 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009570}
Chris Lattner3d69f462004-03-12 05:52:32 +00009571
Chris Lattner69ea9d22008-04-30 06:39:11 +00009572Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9573 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009574 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009575 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009576 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009577 return MI;
9578 }
9579
9580 // Extract the length and alignment and fill if they are constant.
9581 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9582 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009583 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009584 return 0;
9585 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009586 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009587
9588 // If the length is zero, this is a no-op
9589 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9590
9591 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9592 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009593 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009594
9595 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009596 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009597
9598 // Alignment 0 is identity for alignment 1 for memset, but not store.
9599 if (Alignment == 0) Alignment = 1;
9600
9601 // Extract the fill value and store.
9602 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009603 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009604 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009605
9606 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009607 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009608 return MI;
9609 }
9610
9611 return 0;
9612}
9613
9614
Chris Lattner8b0ea312006-01-13 20:11:04 +00009615/// visitCallInst - CallInst simplification. This mostly only handles folding
9616/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9617/// the heavy lifting.
9618///
Chris Lattner9fe38862003-06-19 17:00:31 +00009619Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009620 // If the caller function is nounwind, mark the call as nounwind, even if the
9621 // callee isn't.
9622 if (CI.getParent()->getParent()->doesNotThrow() &&
9623 !CI.doesNotThrow()) {
9624 CI.setDoesNotThrow();
9625 return &CI;
9626 }
9627
Chris Lattner8b0ea312006-01-13 20:11:04 +00009628 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9629 if (!II) return visitCallSite(&CI);
9630
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009631 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9632 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009633 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009634 bool Changed = false;
9635
9636 // memmove/cpy/set of zero bytes is a noop.
9637 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9638 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9639
Chris Lattner35b9e482004-10-12 04:52:52 +00009640 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009641 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009642 // Replace the instruction with just byte operations. We would
9643 // transform other cases to loads/stores, but we don't know if
9644 // alignment is sufficient.
9645 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009646 }
9647
Chris Lattner35b9e482004-10-12 04:52:52 +00009648 // If we have a memmove and the source operation is a constant global,
9649 // then the source and dest pointers can't alias, so we can change this
9650 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009651 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009652 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9653 if (GVSrc->isConstant()) {
9654 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009655 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9656 const Type *Tys[1];
9657 Tys[0] = CI.getOperand(3)->getType();
9658 CI.setOperand(0,
9659 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009660 Changed = true;
9661 }
Chris Lattnera935db82008-05-28 05:30:41 +00009662
9663 // memmove(x,x,size) -> noop.
9664 if (MMI->getSource() == MMI->getDest())
9665 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009666 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009667
Chris Lattner95a959d2006-03-06 20:18:44 +00009668 // If we can determine a pointer alignment that is bigger than currently
9669 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009670 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009671 if (Instruction *I = SimplifyMemTransfer(MI))
9672 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009673 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9674 if (Instruction *I = SimplifyMemSet(MSI))
9675 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009676 }
9677
Chris Lattner8b0ea312006-01-13 20:11:04 +00009678 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009679 }
9680
9681 switch (II->getIntrinsicID()) {
9682 default: break;
9683 case Intrinsic::bswap:
9684 // bswap(bswap(x)) -> x
9685 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9686 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9687 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9688 break;
9689 case Intrinsic::ppc_altivec_lvx:
9690 case Intrinsic::ppc_altivec_lvxl:
9691 case Intrinsic::x86_sse_loadu_ps:
9692 case Intrinsic::x86_sse2_loadu_pd:
9693 case Intrinsic::x86_sse2_loadu_dq:
9694 // Turn PPC lvx -> load if the pointer is known aligned.
9695 // Turn X86 loadups -> load if the pointer is known aligned.
9696 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009697 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9698 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009699 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009700 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009701 break;
9702 case Intrinsic::ppc_altivec_stvx:
9703 case Intrinsic::ppc_altivec_stvxl:
9704 // Turn stvx -> store if the pointer is known aligned.
9705 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9706 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009707 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009708 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009709 return new StoreInst(II->getOperand(1), Ptr);
9710 }
9711 break;
9712 case Intrinsic::x86_sse_storeu_ps:
9713 case Intrinsic::x86_sse2_storeu_pd:
9714 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009715 // Turn X86 storeu -> store if the pointer is known aligned.
9716 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9717 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009718 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009719 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009720 return new StoreInst(II->getOperand(2), Ptr);
9721 }
9722 break;
9723
9724 case Intrinsic::x86_sse_cvttss2si: {
9725 // These intrinsics only demands the 0th element of its input vector. If
9726 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009727 unsigned VWidth =
9728 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9729 APInt DemandedElts(VWidth, 1);
9730 APInt UndefElts(VWidth, 0);
9731 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009732 UndefElts)) {
9733 II->setOperand(1, V);
9734 return II;
9735 }
9736 break;
9737 }
9738
9739 case Intrinsic::ppc_altivec_vperm:
9740 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9741 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9742 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009743
Chris Lattner0521e3c2008-06-18 04:33:20 +00009744 // Check that all of the elements are integer constants or undefs.
9745 bool AllEltsOk = true;
9746 for (unsigned i = 0; i != 16; ++i) {
9747 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9748 !isa<UndefValue>(Mask->getOperand(i))) {
9749 AllEltsOk = false;
9750 break;
9751 }
9752 }
9753
9754 if (AllEltsOk) {
9755 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009756 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9757 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009758 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009759
Chris Lattner0521e3c2008-06-18 04:33:20 +00009760 // Only extract each element once.
9761 Value *ExtractedElts[32];
9762 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9763
Chris Lattnere2ed0572006-04-06 19:19:17 +00009764 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009765 if (isa<UndefValue>(Mask->getOperand(i)))
9766 continue;
9767 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9768 Idx &= 31; // Match the hardware behavior.
9769
9770 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009771 ExtractedElts[Idx] =
9772 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9773 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9774 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009775 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009776
Chris Lattner0521e3c2008-06-18 04:33:20 +00009777 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009778 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9779 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9780 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009781 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009782 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009783 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009784 }
9785 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009786
Chris Lattner0521e3c2008-06-18 04:33:20 +00009787 case Intrinsic::stackrestore: {
9788 // If the save is right next to the restore, remove the restore. This can
9789 // happen when variable allocas are DCE'd.
9790 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9791 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9792 BasicBlock::iterator BI = SS;
9793 if (&*++BI == II)
9794 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009795 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009796 }
9797
9798 // Scan down this block to see if there is another stack restore in the
9799 // same block without an intervening call/alloca.
9800 BasicBlock::iterator BI = II;
9801 TerminatorInst *TI = II->getParent()->getTerminator();
9802 bool CannotRemove = false;
9803 for (++BI; &*BI != TI; ++BI) {
9804 if (isa<AllocaInst>(BI)) {
9805 CannotRemove = true;
9806 break;
9807 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009808 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9809 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9810 // If there is a stackrestore below this one, remove this one.
9811 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9812 return EraseInstFromFunction(CI);
9813 // Otherwise, ignore the intrinsic.
9814 } else {
9815 // If we found a non-intrinsic call, we can't remove the stack
9816 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009817 CannotRemove = true;
9818 break;
9819 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009820 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009821 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009822
9823 // If the stack restore is in a return/unwind block and if there are no
9824 // allocas or calls between the restore and the return, nuke the restore.
9825 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9826 return EraseInstFromFunction(CI);
9827 break;
9828 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009829 }
9830
Chris Lattner8b0ea312006-01-13 20:11:04 +00009831 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009832}
9833
9834// InvokeInst simplification
9835//
9836Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009837 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009838}
9839
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009840/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9841/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009842static bool isSafeToEliminateVarargsCast(const CallSite CS,
9843 const CastInst * const CI,
9844 const TargetData * const TD,
9845 const int ix) {
9846 if (!CI->isLosslessCast())
9847 return false;
9848
9849 // The size of ByVal arguments is derived from the type, so we
9850 // can't change to a type with a different size. If the size were
9851 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009852 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009853 return true;
9854
9855 const Type* SrcTy =
9856 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9857 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9858 if (!SrcTy->isSized() || !DstTy->isSized())
9859 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009860 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009861 return false;
9862 return true;
9863}
9864
Chris Lattnera44d8a22003-10-07 22:32:43 +00009865// visitCallSite - Improvements for call and invoke instructions.
9866//
9867Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009868 bool Changed = false;
9869
9870 // If the callee is a constexpr cast of a function, attempt to move the cast
9871 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009872 if (transformConstExprCastCall(CS)) return 0;
9873
Chris Lattner6c266db2003-10-07 22:54:13 +00009874 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009875
Chris Lattner08b22ec2005-05-13 07:09:09 +00009876 if (Function *CalleeF = dyn_cast<Function>(Callee))
9877 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9878 Instruction *OldCall = CS.getInstruction();
9879 // If the call and callee calling conventions don't match, this call must
9880 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009881 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009882 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009883 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009884 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009885 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009886 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9887 return EraseInstFromFunction(*OldCall);
9888 return 0;
9889 }
9890
Chris Lattner17be6352004-10-18 02:59:09 +00009891 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9892 // This instruction is not reachable, just remove it. We insert a store to
9893 // undef so that we know that this code is not reachable, despite the fact
9894 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009895 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009896 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009897 CS.getInstruction());
9898
9899 if (!CS.getInstruction()->use_empty())
9900 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009901 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009902
9903 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9904 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009905 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009906 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009907 }
Chris Lattner17be6352004-10-18 02:59:09 +00009908 return EraseInstFromFunction(*CS.getInstruction());
9909 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009910
Duncan Sandscdb6d922007-09-17 10:26:40 +00009911 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9912 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9913 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9914 return transformCallThroughTrampoline(CS);
9915
Chris Lattner6c266db2003-10-07 22:54:13 +00009916 const PointerType *PTy = cast<PointerType>(Callee->getType());
9917 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9918 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009919 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009920 // See if we can optimize any arguments passed through the varargs area of
9921 // the call.
9922 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009923 E = CS.arg_end(); I != E; ++I, ++ix) {
9924 CastInst *CI = dyn_cast<CastInst>(*I);
9925 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9926 *I = CI->getOperand(0);
9927 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009928 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009929 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009930 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009931
Duncan Sandsf0c33542007-12-19 21:13:37 +00009932 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009933 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009934 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009935 Changed = true;
9936 }
9937
Chris Lattner6c266db2003-10-07 22:54:13 +00009938 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009939}
9940
Chris Lattner9fe38862003-06-19 17:00:31 +00009941// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9942// attempt to move the cast to the arguments of the call/invoke.
9943//
9944bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9945 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9946 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009947 if (CE->getOpcode() != Instruction::BitCast ||
9948 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009949 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009950 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009951 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009952 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009953
9954 // Okay, this is a cast from a function to a different type. Unless doing so
9955 // would cause a type conversion of one of our arguments, change this call to
9956 // be a direct call with arguments casted to the appropriate types.
9957 //
9958 const FunctionType *FT = Callee->getFunctionType();
9959 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009960 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009961
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009962 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009963 return false; // TODO: Handle multiple return values.
9964
Chris Lattnerf78616b2004-01-14 06:06:08 +00009965 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009966 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009967 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009968 // Conversion is ok if changing from one pointer type to another or from
9969 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009970 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009971 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009972 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009973 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00009974 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009975
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009976 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009977 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +00009978 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009979 return false; // Cannot transform this return value.
9980
Chris Lattner58d74912008-03-12 17:45:29 +00009981 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009982 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009983 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009984 return false; // Attribute not compatible with transformed value.
9985 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009986
Chris Lattnerf78616b2004-01-14 06:06:08 +00009987 // If the callsite is an invoke instruction, and the return value is used by
9988 // a PHI node in a successor, we cannot change the return type of the call
9989 // because there is no place to put the cast instruction (without breaking
9990 // the critical edge). Bail out in this case.
9991 if (!Caller->use_empty())
9992 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9993 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9994 UI != E; ++UI)
9995 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9996 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009997 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009998 return false;
9999 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010000
10001 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10002 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010003
Chris Lattner9fe38862003-06-19 17:00:31 +000010004 CallSite::arg_iterator AI = CS.arg_begin();
10005 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10006 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010007 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010008
10009 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010010 return false; // Cannot transform this parameter value.
10011
Devang Patel19c87462008-09-26 22:53:05 +000010012 if (CallerPAL.getParamAttributes(i + 1)
10013 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010014 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010015
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010016 // Converting from one pointer type to another or between a pointer and an
10017 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010018 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010019 (TD && ((isa<PointerType>(ParamTy) ||
10020 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10021 (isa<PointerType>(ActTy) ||
10022 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010023 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010024 }
10025
10026 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010027 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010028 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010029
Chris Lattner58d74912008-03-12 17:45:29 +000010030 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10031 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010032 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010033 // won't be dropping them. Check that these extra arguments have attributes
10034 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010035 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10036 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010037 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010038 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010039 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010040 return false;
10041 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010042
Chris Lattner9fe38862003-06-19 17:00:31 +000010043 // Okay, we decided that this is a safe thing to do: go ahead and start
10044 // inserting cast instructions as necessary...
10045 std::vector<Value*> Args;
10046 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010047 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010048 attrVec.reserve(NumCommonArgs);
10049
10050 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010051 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010052
10053 // If the return value is not being used, the type may not be compatible
10054 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010055 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010056
10057 // Add the new return attributes.
10058 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010059 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010060
10061 AI = CS.arg_begin();
10062 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10063 const Type *ParamTy = FT->getParamType(i);
10064 if ((*AI)->getType() == ParamTy) {
10065 Args.push_back(*AI);
10066 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010067 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010068 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010069 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010070 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010071
10072 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010073 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010074 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010075 }
10076
10077 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010078 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010079 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010080 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010081
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010082 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010083 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010084 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010085 errs() << "WARNING: While resolving call to function '"
10086 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010087 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010088 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010089 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10090 const Type *PTy = getPromotedType((*AI)->getType());
10091 if (PTy != (*AI)->getType()) {
10092 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010093 Instruction::CastOps opcode =
10094 CastInst::getCastOpcode(*AI, false, PTy, false);
10095 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010096 } else {
10097 Args.push_back(*AI);
10098 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010099
Duncan Sandse1e520f2008-01-13 08:02:44 +000010100 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010101 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010102 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010103 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010104 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010105 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010106
Devang Patel19c87462008-09-26 22:53:05 +000010107 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10108 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10109
Owen Anderson1d0be152009-08-13 21:58:54 +000010110 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010111 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010112
Eric Christophera66297a2009-07-25 02:45:27 +000010113 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10114 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010115
Chris Lattner9fe38862003-06-19 17:00:31 +000010116 Instruction *NC;
10117 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010118 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010119 Args.begin(), Args.end(),
10120 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010121 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010122 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010123 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010124 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10125 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010126 CallInst *CI = cast<CallInst>(Caller);
10127 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010128 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010129 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010130 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010131 }
10132
Chris Lattner6934a042007-02-11 01:23:03 +000010133 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010134 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010135 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010136 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010137 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010138 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010139 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010140
10141 // If this is an invoke instruction, we should insert it after the first
10142 // non-phi, instruction in the normal successor block.
10143 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010144 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010145 InsertNewInstBefore(NC, *I);
10146 } else {
10147 // Otherwise, it's a call, just insert cast right after the call instr
10148 InsertNewInstBefore(NC, *Caller);
10149 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010150 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010151 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010152 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010153 }
10154 }
10155
Chris Lattner931f8f32009-08-31 05:17:58 +000010156
10157 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010158 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010159
10160 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010161 return true;
10162}
10163
Duncan Sandscdb6d922007-09-17 10:26:40 +000010164// transformCallThroughTrampoline - Turn a call to a function created by the
10165// init_trampoline intrinsic into a direct call to the underlying function.
10166//
10167Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10168 Value *Callee = CS.getCalledValue();
10169 const PointerType *PTy = cast<PointerType>(Callee->getType());
10170 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010171 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010172
10173 // If the call already has the 'nest' attribute somewhere then give up -
10174 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010175 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010176 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010177
10178 IntrinsicInst *Tramp =
10179 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10180
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010181 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010182 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10183 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10184
Devang Patel05988662008-09-25 21:00:45 +000010185 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010186 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010187 unsigned NestIdx = 1;
10188 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010189 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010190
10191 // Look for a parameter marked with the 'nest' attribute.
10192 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10193 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010194 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010195 // Record the parameter type and any other attributes.
10196 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010197 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010198 break;
10199 }
10200
10201 if (NestTy) {
10202 Instruction *Caller = CS.getInstruction();
10203 std::vector<Value*> NewArgs;
10204 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10205
Devang Patel05988662008-09-25 21:00:45 +000010206 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010207 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010208
Duncan Sandscdb6d922007-09-17 10:26:40 +000010209 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010210 // mean appending it. Likewise for attributes.
10211
Devang Patel19c87462008-09-26 22:53:05 +000010212 // Add any result attributes.
10213 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010214 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010215
Duncan Sandscdb6d922007-09-17 10:26:40 +000010216 {
10217 unsigned Idx = 1;
10218 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10219 do {
10220 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010221 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010222 Value *NestVal = Tramp->getOperand(3);
10223 if (NestVal->getType() != NestTy)
10224 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10225 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010226 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010227 }
10228
10229 if (I == E)
10230 break;
10231
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010232 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010233 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010234 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010235 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010236 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010237
10238 ++Idx, ++I;
10239 } while (1);
10240 }
10241
Devang Patel19c87462008-09-26 22:53:05 +000010242 // Add any function attributes.
10243 if (Attributes Attr = Attrs.getFnAttributes())
10244 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10245
Duncan Sandscdb6d922007-09-17 10:26:40 +000010246 // The trampoline may have been bitcast to a bogus type (FTy).
10247 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010248 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010249
Duncan Sandscdb6d922007-09-17 10:26:40 +000010250 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010251 NewTypes.reserve(FTy->getNumParams()+1);
10252
Duncan Sandscdb6d922007-09-17 10:26:40 +000010253 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010254 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010255 {
10256 unsigned Idx = 1;
10257 FunctionType::param_iterator I = FTy->param_begin(),
10258 E = FTy->param_end();
10259
10260 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010261 if (Idx == NestIdx)
10262 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010263 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010264
10265 if (I == E)
10266 break;
10267
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010268 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010269 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010270
10271 ++Idx, ++I;
10272 } while (1);
10273 }
10274
10275 // Replace the trampoline call with a direct call. Let the generic
10276 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010277 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010278 FTy->isVarArg());
10279 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010280 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010281 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010282 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010283 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10284 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010285
10286 Instruction *NewCaller;
10287 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010288 NewCaller = InvokeInst::Create(NewCallee,
10289 II->getNormalDest(), II->getUnwindDest(),
10290 NewArgs.begin(), NewArgs.end(),
10291 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010292 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010293 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010294 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010295 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10296 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010297 if (cast<CallInst>(Caller)->isTailCall())
10298 cast<CallInst>(NewCaller)->setTailCall();
10299 cast<CallInst>(NewCaller)->
10300 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010301 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010302 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010303 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010304 Caller->replaceAllUsesWith(NewCaller);
10305 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010306 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010307 return 0;
10308 }
10309 }
10310
10311 // Replace the trampoline call with a direct call. Since there is no 'nest'
10312 // parameter, there is no need to adjust the argument list. Let the generic
10313 // code sort out any function type mismatches.
10314 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010315 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010316 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010317 CS.setCalledFunction(NewCallee);
10318 return CS.getInstruction();
10319}
10320
Chris Lattner7da52b22006-11-01 04:51:18 +000010321/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10322/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10323/// and a single binop.
10324Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10325 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010326 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010327 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010328 Value *LHSVal = FirstInst->getOperand(0);
10329 Value *RHSVal = FirstInst->getOperand(1);
10330
10331 const Type *LHSType = LHSVal->getType();
10332 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010333
10334 // Scan to see if all operands are the same opcode, all have one use, and all
10335 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010336 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010337 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010338 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010339 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010340 // types or GEP's with different index types.
10341 I->getOperand(0)->getType() != LHSType ||
10342 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010343 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010344
10345 // If they are CmpInst instructions, check their predicates
10346 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10347 if (cast<CmpInst>(I)->getPredicate() !=
10348 cast<CmpInst>(FirstInst)->getPredicate())
10349 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010350
10351 // Keep track of which operand needs a phi node.
10352 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10353 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010354 }
10355
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010356 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010357
Chris Lattner7da52b22006-11-01 04:51:18 +000010358 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010359 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010360 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010361 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010362 NewLHS = PHINode::Create(LHSType,
10363 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010364 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10365 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010366 InsertNewInstBefore(NewLHS, PN);
10367 LHSVal = NewLHS;
10368 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010369
10370 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010371 NewRHS = PHINode::Create(RHSType,
10372 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010373 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10374 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010375 InsertNewInstBefore(NewRHS, PN);
10376 RHSVal = NewRHS;
10377 }
10378
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010379 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010380 if (NewLHS || NewRHS) {
10381 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10382 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10383 if (NewLHS) {
10384 Value *NewInLHS = InInst->getOperand(0);
10385 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10386 }
10387 if (NewRHS) {
10388 Value *NewInRHS = InInst->getOperand(1);
10389 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10390 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010391 }
10392 }
10393
Chris Lattner7da52b22006-11-01 04:51:18 +000010394 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010395 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010396 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010397 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010398 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010399}
10400
Chris Lattner05f18922008-12-01 02:34:36 +000010401Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10402 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10403
10404 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10405 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010406 // This is true if all GEP bases are allocas and if all indices into them are
10407 // constants.
10408 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010409
10410 // Scan to see if all operands are the same opcode, all have one use, and all
10411 // kill their operands (i.e. the operands have one use).
10412 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10413 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10414 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10415 GEP->getNumOperands() != FirstInst->getNumOperands())
10416 return 0;
10417
Chris Lattner36d3e322009-02-21 00:46:50 +000010418 // Keep track of whether or not all GEPs are of alloca pointers.
10419 if (AllBasePointersAreAllocas &&
10420 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10421 !GEP->hasAllConstantIndices()))
10422 AllBasePointersAreAllocas = false;
10423
Chris Lattner05f18922008-12-01 02:34:36 +000010424 // Compare the operand lists.
10425 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10426 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10427 continue;
10428
10429 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10430 // if one of the PHIs has a constant for the index. The index may be
10431 // substantially cheaper to compute for the constants, so making it a
10432 // variable index could pessimize the path. This also handles the case
10433 // for struct indices, which must always be constant.
10434 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10435 isa<ConstantInt>(GEP->getOperand(op)))
10436 return 0;
10437
10438 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10439 return 0;
10440 FixedOperands[op] = 0; // Needs a PHI.
10441 }
10442 }
10443
Chris Lattner36d3e322009-02-21 00:46:50 +000010444 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010445 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010446 // offset calculation, but all the predecessors will have to materialize the
10447 // stack address into a register anyway. We'd actually rather *clone* the
10448 // load up into the predecessors so that we have a load of a gep of an alloca,
10449 // which can usually all be folded into the load.
10450 if (AllBasePointersAreAllocas)
10451 return 0;
10452
Chris Lattner05f18922008-12-01 02:34:36 +000010453 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10454 // that is variable.
10455 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10456
10457 bool HasAnyPHIs = false;
10458 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10459 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10460 Value *FirstOp = FirstInst->getOperand(i);
10461 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10462 FirstOp->getName()+".pn");
10463 InsertNewInstBefore(NewPN, PN);
10464
10465 NewPN->reserveOperandSpace(e);
10466 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10467 OperandPhis[i] = NewPN;
10468 FixedOperands[i] = NewPN;
10469 HasAnyPHIs = true;
10470 }
10471
10472
10473 // Add all operands to the new PHIs.
10474 if (HasAnyPHIs) {
10475 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10476 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10477 BasicBlock *InBB = PN.getIncomingBlock(i);
10478
10479 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10480 if (PHINode *OpPhi = OperandPhis[op])
10481 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10482 }
10483 }
10484
10485 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010486 GetElementPtrInst *GEP =
10487 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10488 FixedOperands.end());
10489 if (cast<GEPOperator>(FirstInst)->isInBounds())
10490 cast<GEPOperator>(GEP)->setIsInBounds(true);
10491 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010492}
10493
10494
Chris Lattner21550882009-02-23 05:56:17 +000010495/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10496/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010497/// obvious the value of the load is not changed from the point of the load to
10498/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010499///
10500/// Finally, it is safe, but not profitable, to sink a load targetting a
10501/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10502/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010503static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010504 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10505
10506 for (++BBI; BBI != E; ++BBI)
10507 if (BBI->mayWriteToMemory())
10508 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010509
10510 // Check for non-address taken alloca. If not address-taken already, it isn't
10511 // profitable to do this xform.
10512 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10513 bool isAddressTaken = false;
10514 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10515 UI != E; ++UI) {
10516 if (isa<LoadInst>(UI)) continue;
10517 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10518 // If storing TO the alloca, then the address isn't taken.
10519 if (SI->getOperand(1) == AI) continue;
10520 }
10521 isAddressTaken = true;
10522 break;
10523 }
10524
Chris Lattner36d3e322009-02-21 00:46:50 +000010525 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010526 return false;
10527 }
10528
Chris Lattner36d3e322009-02-21 00:46:50 +000010529 // If this load is a load from a GEP with a constant offset from an alloca,
10530 // then we don't want to sink it. In its present form, it will be
10531 // load [constant stack offset]. Sinking it will cause us to have to
10532 // materialize the stack addresses in each predecessor in a register only to
10533 // do a shared load from register in the successor.
10534 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10535 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10536 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10537 return false;
10538
Chris Lattner76c73142006-11-01 07:13:54 +000010539 return true;
10540}
10541
Chris Lattner9fe38862003-06-19 17:00:31 +000010542
Chris Lattnerbac32862004-11-14 19:13:23 +000010543// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10544// operator and they all are only used by the PHI, PHI together their
10545// inputs, and do the operation once, to the result of the PHI.
10546Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10547 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10548
10549 // Scan the instruction, looking for input operations that can be folded away.
10550 // If all input operands to the phi are the same instruction (e.g. a cast from
10551 // the same type or "+42") we can pull the operation through the PHI, reducing
10552 // code size and simplifying code.
10553 Constant *ConstantOp = 0;
10554 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010555 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010556 if (isa<CastInst>(FirstInst)) {
10557 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010558 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010559 // Can fold binop, compare or shift here if the RHS is a constant,
10560 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010561 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010562 if (ConstantOp == 0)
10563 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010564 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10565 isVolatile = LI->isVolatile();
10566 // We can't sink the load if the loaded value could be modified between the
10567 // load and the PHI.
10568 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010569 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010570 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010571
10572 // If the PHI is of volatile loads and the load block has multiple
10573 // successors, sinking it would remove a load of the volatile value from
10574 // the path through the other successor.
10575 if (isVolatile &&
10576 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10577 return 0;
10578
Chris Lattner9c080502006-11-01 07:43:41 +000010579 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010580 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010581 } else {
10582 return 0; // Cannot fold this operation.
10583 }
10584
10585 // Check to see if all arguments are the same operation.
10586 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10587 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10588 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010589 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010590 return 0;
10591 if (CastSrcTy) {
10592 if (I->getOperand(0)->getType() != CastSrcTy)
10593 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010594 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010595 // We can't sink the load if the loaded value could be modified between
10596 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010597 if (LI->isVolatile() != isVolatile ||
10598 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010599 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010600 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010601
Chris Lattner71042962008-07-08 17:18:32 +000010602 // If the PHI is of volatile loads and the load block has multiple
10603 // successors, sinking it would remove a load of the volatile value from
10604 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010605 if (isVolatile &&
10606 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10607 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010608
Chris Lattnerbac32862004-11-14 19:13:23 +000010609 } else if (I->getOperand(1) != ConstantOp) {
10610 return 0;
10611 }
10612 }
10613
10614 // Okay, they are all the same operation. Create a new PHI node of the
10615 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010616 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10617 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010618 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010619
10620 Value *InVal = FirstInst->getOperand(0);
10621 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010622
10623 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010624 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10625 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10626 if (NewInVal != InVal)
10627 InVal = 0;
10628 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10629 }
10630
10631 Value *PhiVal;
10632 if (InVal) {
10633 // The new PHI unions all of the same values together. This is really
10634 // common, so we handle it intelligently here for compile-time speed.
10635 PhiVal = InVal;
10636 delete NewPN;
10637 } else {
10638 InsertNewInstBefore(NewPN, PN);
10639 PhiVal = NewPN;
10640 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010641
Chris Lattnerbac32862004-11-14 19:13:23 +000010642 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010643 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010644 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010645 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010646 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010647 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010648 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010649 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010650 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10651
10652 // If this was a volatile load that we are merging, make sure to loop through
10653 // and mark all the input loads as non-volatile. If we don't do this, we will
10654 // insert a new volatile load and the old ones will not be deletable.
10655 if (isVolatile)
10656 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10657 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10658
10659 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010660}
Chris Lattnera1be5662002-05-02 17:06:02 +000010661
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010662/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10663/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010664static bool DeadPHICycle(PHINode *PN,
10665 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010666 if (PN->use_empty()) return true;
10667 if (!PN->hasOneUse()) return false;
10668
10669 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010670 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010671 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010672
10673 // Don't scan crazily complex things.
10674 if (PotentiallyDeadPHIs.size() == 16)
10675 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010676
10677 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10678 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010679
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010680 return false;
10681}
10682
Chris Lattnercf5008a2007-11-06 21:52:06 +000010683/// PHIsEqualValue - Return true if this phi node is always equal to
10684/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10685/// z = some value; x = phi (y, z); y = phi (x, z)
10686static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10687 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10688 // See if we already saw this PHI node.
10689 if (!ValueEqualPHIs.insert(PN))
10690 return true;
10691
10692 // Don't scan crazily complex things.
10693 if (ValueEqualPHIs.size() == 16)
10694 return false;
10695
10696 // Scan the operands to see if they are either phi nodes or are equal to
10697 // the value.
10698 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10699 Value *Op = PN->getIncomingValue(i);
10700 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10701 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10702 return false;
10703 } else if (Op != NonPhiInVal)
10704 return false;
10705 }
10706
10707 return true;
10708}
10709
10710
Chris Lattner473945d2002-05-06 18:06:38 +000010711// PHINode simplification
10712//
Chris Lattner7e708292002-06-25 16:13:24 +000010713Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010714 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010715 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010716
Owen Anderson7e057142006-07-10 22:03:18 +000010717 if (Value *V = PN.hasConstantValue())
10718 return ReplaceInstUsesWith(PN, V);
10719
Owen Anderson7e057142006-07-10 22:03:18 +000010720 // If all PHI operands are the same operation, pull them through the PHI,
10721 // reducing code size.
10722 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010723 isa<Instruction>(PN.getIncomingValue(1)) &&
10724 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10725 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10726 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10727 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010728 PN.getIncomingValue(0)->hasOneUse())
10729 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10730 return Result;
10731
10732 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10733 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10734 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010735 if (PN.hasOneUse()) {
10736 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10737 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010738 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010739 PotentiallyDeadPHIs.insert(&PN);
10740 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010741 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010742 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010743
10744 // If this phi has a single use, and if that use just computes a value for
10745 // the next iteration of a loop, delete the phi. This occurs with unused
10746 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10747 // common case here is good because the only other things that catch this
10748 // are induction variable analysis (sometimes) and ADCE, which is only run
10749 // late.
10750 if (PHIUser->hasOneUse() &&
10751 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10752 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010753 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010754 }
10755 }
Owen Anderson7e057142006-07-10 22:03:18 +000010756
Chris Lattnercf5008a2007-11-06 21:52:06 +000010757 // We sometimes end up with phi cycles that non-obviously end up being the
10758 // same value, for example:
10759 // z = some value; x = phi (y, z); y = phi (x, z)
10760 // where the phi nodes don't necessarily need to be in the same block. Do a
10761 // quick check to see if the PHI node only contains a single non-phi value, if
10762 // so, scan to see if the phi cycle is actually equal to that value.
10763 {
10764 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10765 // Scan for the first non-phi operand.
10766 while (InValNo != NumOperandVals &&
10767 isa<PHINode>(PN.getIncomingValue(InValNo)))
10768 ++InValNo;
10769
10770 if (InValNo != NumOperandVals) {
10771 Value *NonPhiInVal = PN.getOperand(InValNo);
10772
10773 // Scan the rest of the operands to see if there are any conflicts, if so
10774 // there is no need to recursively scan other phis.
10775 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10776 Value *OpVal = PN.getIncomingValue(InValNo);
10777 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10778 break;
10779 }
10780
10781 // If we scanned over all operands, then we have one unique value plus
10782 // phi values. Scan PHI nodes to see if they all merge in each other or
10783 // the value.
10784 if (InValNo == NumOperandVals) {
10785 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10786 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10787 return ReplaceInstUsesWith(PN, NonPhiInVal);
10788 }
10789 }
10790 }
Chris Lattner60921c92003-12-19 05:58:40 +000010791 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010792}
10793
Chris Lattner7e708292002-06-25 16:13:24 +000010794Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010795 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010796 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010797 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010798 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010799
Chris Lattnere87597f2004-10-16 18:11:37 +000010800 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010801 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010802
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010803 bool HasZeroPointerIndex = false;
10804 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10805 HasZeroPointerIndex = C->isNullValue();
10806
10807 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010808 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010809
Chris Lattner28977af2004-04-05 01:30:19 +000010810 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010811 if (TD) {
10812 bool MadeChange = false;
10813 unsigned PtrSize = TD->getPointerSizeInBits();
10814
10815 gep_type_iterator GTI = gep_type_begin(GEP);
10816 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10817 I != E; ++I, ++GTI) {
10818 if (!isa<SequentialType>(*GTI)) continue;
10819
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010820 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010821 // to what we need. If narrower, sign-extend it to what we need. This
10822 // explicit cast can make subsequent optimizations more obvious.
10823 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010824 if (OpBits == PtrSize)
10825 continue;
10826
Chris Lattner2345d1d2009-08-30 20:01:10 +000010827 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010828 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010829 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010830 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010831 }
Chris Lattner28977af2004-04-05 01:30:19 +000010832
Chris Lattner90ac28c2002-08-02 19:29:35 +000010833 // Combine Indices - If the source pointer to this getelementptr instruction
10834 // is a getelementptr instruction, combine the indices of the two
10835 // getelementptr instructions into a single instruction.
10836 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010837 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010838 // Note that if our source is a gep chain itself that we wait for that
10839 // chain to be resolved before we perform this transformation. This
10840 // avoids us creating a TON of code in some cases.
10841 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010842 if (GetElementPtrInst *SrcGEP =
10843 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10844 if (SrcGEP->getNumOperands() == 2)
10845 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010846
Chris Lattner72588fc2007-02-15 22:48:32 +000010847 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010848
10849 // Find out whether the last index in the source GEP is a sequential idx.
10850 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010851 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10852 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010853 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010854
Chris Lattner90ac28c2002-08-02 19:29:35 +000010855 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010856 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010857 // Replace: gep (gep %P, long B), long A, ...
10858 // With: T = long A+B; gep %P, T, ...
10859 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010860 Value *Sum;
10861 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10862 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010863 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010864 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010865 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010866 Sum = SO1;
10867 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010868 // If they aren't the same type, then the input hasn't been processed
10869 // by the loop above yet (which canonicalizes sequential index types to
10870 // intptr_t). Just avoid transforming this until the input has been
10871 // normalized.
10872 if (SO1->getType() != GO1->getType())
10873 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010874 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010875 }
Chris Lattner620ce142004-05-07 22:09:22 +000010876
Chris Lattnerab984842009-08-30 05:30:55 +000010877 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010878 if (Src->getNumOperands() == 2) {
10879 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010880 GEP.setOperand(1, Sum);
10881 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010882 }
Chris Lattnerab984842009-08-30 05:30:55 +000010883 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010884 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010885 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010886 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010887 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010888 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010889 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010890 Indices.append(Src->op_begin()+1, Src->op_end());
10891 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010892 }
10893
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010894 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000010895 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010896 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010897 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010898 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010899 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10900 return NewGEP;
10901 }
Chris Lattner6e24d832009-08-30 05:00:50 +000010902 }
10903
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010904 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10905 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010906 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010907
Chris Lattner2de23192009-08-30 20:38:21 +000010908 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10909 // want to change the gep until the bitcasts are eliminated.
10910 if (getBitCastOperand(X)) {
10911 Worklist.AddValue(PtrOp);
10912 return 0;
10913 }
10914
Chris Lattner963f4ba2009-08-30 20:36:46 +000010915 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10916 // into : GEP [10 x i8]* X, i32 0, ...
10917 //
10918 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10919 // into : GEP i8* X, ...
10920 //
10921 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000010922 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000010923 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10924 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010925 if (const ArrayType *CATy =
10926 dyn_cast<ArrayType>(CPTy->getElementType())) {
10927 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10928 if (CATy->getElementType() == XTy->getElementType()) {
10929 // -> GEP i8* X, ...
10930 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010931 GetElementPtrInst *NewGEP =
10932 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10933 GEP.getName());
10934 if (cast<GEPOperator>(&GEP)->isInBounds())
10935 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10936 return NewGEP;
Chris Lattner963f4ba2009-08-30 20:36:46 +000010937 }
10938
10939 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010940 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010941 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010942 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010943 // At this point, we know that the cast source type is a pointer
10944 // to an array of the same type as the destination pointer
10945 // array. Because the array type is never stepped over (there
10946 // is a leading zero) we can fold the cast into this GEP.
10947 GEP.setOperand(0, X);
10948 return &GEP;
10949 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010950 }
10951 }
Chris Lattnereed48272005-09-13 00:40:14 +000010952 } else if (GEP.getNumOperands() == 2) {
10953 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010954 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10955 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010956 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10957 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010958 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000010959 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10960 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010961 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000010962 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000010963 Idx[1] = GEP.getOperand(1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010964 Value *NewGEP =
10965 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010966 if (cast<GEPOperator>(&GEP)->isInBounds())
10967 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000010968 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010969 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010970 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010971
10972 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010973 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010974 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010975 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010976
Owen Anderson1d0be152009-08-13 21:58:54 +000010977 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010978 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000010979 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010980
10981 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10982 // allow either a mul, shift, or constant here.
10983 Value *NewIdx = 0;
10984 ConstantInt *Scale = 0;
10985 if (ArrayEltSize == 1) {
10986 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000010987 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010988 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010989 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010990 Scale = CI;
10991 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10992 if (Inst->getOpcode() == Instruction::Shl &&
10993 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010994 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10995 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000010996 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000010997 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010998 NewIdx = Inst->getOperand(0);
10999 } else if (Inst->getOpcode() == Instruction::Mul &&
11000 isa<ConstantInt>(Inst->getOperand(1))) {
11001 Scale = cast<ConstantInt>(Inst->getOperand(1));
11002 NewIdx = Inst->getOperand(0);
11003 }
11004 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011005
Chris Lattner7835cdd2005-09-13 18:36:04 +000011006 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011007 // out, perform the transformation. Note, we don't know whether Scale is
11008 // signed or not. We'll use unsigned version of division/modulo
11009 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011010 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011011 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011012 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011013 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011014 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011015 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11016 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011017 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011018 }
11019
11020 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011021 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011022 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011023 Idx[1] = NewIdx;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011024 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011025 if (cast<GEPOperator>(&GEP)->isInBounds())
11026 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011027 // The NewGEP must be pointer typed, so must the old one -> BitCast
11028 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011029 }
11030 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011031 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011032 }
Chris Lattner58407792009-01-09 04:53:57 +000011033
Chris Lattner46cd5a12009-01-09 05:44:56 +000011034 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011035 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011036 /// Y = gep X, <...constant indices...>
11037 /// into a gep of the original struct. This is important for SROA and alias
11038 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011039 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011040 if (TD &&
11041 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011042 // Determine how much the GEP moves the pointer. We are guaranteed to get
11043 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011044 ConstantInt *OffsetV =
11045 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011046 int64_t Offset = OffsetV->getSExtValue();
11047
11048 // If this GEP instruction doesn't move the pointer, just replace the GEP
11049 // with a bitcast of the real input to the dest type.
11050 if (Offset == 0) {
11051 // If the bitcast is of an allocation, and the allocation will be
11052 // converted to match the type of the cast, don't touch this.
11053 if (isa<AllocationInst>(BCI->getOperand(0))) {
11054 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11055 if (Instruction *I = visitBitCast(*BCI)) {
11056 if (I != BCI) {
11057 I->takeName(BCI);
11058 BCI->getParent()->getInstList().insert(BCI, I);
11059 ReplaceInstUsesWith(*BCI, I);
11060 }
11061 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011062 }
Chris Lattner58407792009-01-09 04:53:57 +000011063 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011064 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011065 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011066
11067 // Otherwise, if the offset is non-zero, we need to find out if there is a
11068 // field at Offset in 'A's type. If so, we can pull the cast through the
11069 // GEP.
11070 SmallVector<Value*, 8> NewIndices;
11071 const Type *InTy =
11072 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011073 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011074 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11075 NewIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011076 if (cast<GEPOperator>(&GEP)->isInBounds())
11077 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011078
11079 if (NGEP->getType() == GEP.getType())
11080 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011081 NGEP->takeName(&GEP);
11082 return new BitCastInst(NGEP, GEP.getType());
11083 }
Chris Lattner58407792009-01-09 04:53:57 +000011084 }
11085 }
11086
Chris Lattner8a2a3112001-12-14 16:52:21 +000011087 return 0;
11088}
11089
Chris Lattner0864acf2002-11-04 16:18:53 +000011090Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11091 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011092 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011093 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11094 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011095 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011096 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011097
11098 // Create and insert the replacement instruction...
11099 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011100 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011101 else {
11102 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011103 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011104 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011105 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011106
Chris Lattner0864acf2002-11-04 16:18:53 +000011107 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011108 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011109 //
11110 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011111 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011112
11113 // Now that I is pointing to the first non-allocation-inst in the block,
11114 // insert our getelementptr instruction...
11115 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011116 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011117 Value *Idx[2];
11118 Idx[0] = NullIdx;
11119 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011120 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11121 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011122 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011123
11124 // Now make everything use the getelementptr instead of the original
11125 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011126 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011127 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011128 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011129 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011130 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011131
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011132 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011133 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011134 // Note that we only do this for alloca's, because malloc should allocate
11135 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011136 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011137 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011138
11139 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11140 if (AI.getAlignment() == 0)
11141 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11142 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011143
Chris Lattner0864acf2002-11-04 16:18:53 +000011144 return 0;
11145}
11146
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011147Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11148 Value *Op = FI.getOperand(0);
11149
Chris Lattner17be6352004-10-18 02:59:09 +000011150 // free undef -> unreachable.
11151 if (isa<UndefValue>(Op)) {
11152 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011153 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011154 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011155 return EraseInstFromFunction(FI);
11156 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011157
Chris Lattner6160e852004-02-28 04:57:37 +000011158 // If we have 'free null' delete the instruction. This can happen in stl code
11159 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011160 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011161 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011162
11163 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11164 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11165 FI.setOperand(0, CI->getOperand(0));
11166 return &FI;
11167 }
11168
11169 // Change free (gep X, 0,0,0,0) into free(X)
11170 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11171 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011172 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011173 FI.setOperand(0, GEPI->getOperand(0));
11174 return &FI;
11175 }
11176 }
11177
11178 // Change free(malloc) into nothing, if the malloc has a single use.
11179 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11180 if (MI->hasOneUse()) {
11181 EraseInstFromFunction(FI);
11182 return EraseInstFromFunction(*MI);
11183 }
Chris Lattner6160e852004-02-28 04:57:37 +000011184
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011185 return 0;
11186}
11187
11188
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011189/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011190static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011191 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011192 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011193 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011194 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011195
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011196 if (TD) {
11197 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11198 // Instead of loading constant c string, use corresponding integer value
11199 // directly if string length is small enough.
11200 std::string Str;
11201 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11202 unsigned len = Str.length();
11203 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11204 unsigned numBits = Ty->getPrimitiveSizeInBits();
11205 // Replace LI with immediate integer store.
11206 if ((numBits >> 3) == len + 1) {
11207 APInt StrVal(numBits, 0);
11208 APInt SingleChar(numBits, 0);
11209 if (TD->isLittleEndian()) {
11210 for (signed i = len-1; i >= 0; i--) {
11211 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11212 StrVal = (StrVal << 8) | SingleChar;
11213 }
11214 } else {
11215 for (unsigned i = 0; i < len; i++) {
11216 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11217 StrVal = (StrVal << 8) | SingleChar;
11218 }
11219 // Append NULL at the end.
11220 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011221 StrVal = (StrVal << 8) | SingleChar;
11222 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011223 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011224 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011225 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011226 }
11227 }
11228 }
11229
Mon P Wang6753f952009-02-07 22:19:29 +000011230 const PointerType *DestTy = cast<PointerType>(CI->getType());
11231 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011232 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011233
11234 // If the address spaces don't match, don't eliminate the cast.
11235 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11236 return 0;
11237
Chris Lattnerb89e0712004-07-13 01:49:43 +000011238 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011239
Reid Spencer42230162007-01-22 05:51:25 +000011240 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011241 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011242 // If the source is an array, the code below will not succeed. Check to
11243 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11244 // constants.
11245 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11246 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11247 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011248 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011249 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011250 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011251 SrcTy = cast<PointerType>(CastOp->getType());
11252 SrcPTy = SrcTy->getElementType();
11253 }
11254
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011255 if (IC.getTargetData() &&
11256 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011257 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011258 // Do not allow turning this into a load of an integer, which is then
11259 // casted to a pointer, this pessimizes pointer analysis a lot.
11260 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011261 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11262 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011263
Chris Lattnerf9527852005-01-31 04:50:46 +000011264 // Okay, we are casting from one integer or pointer type to another of
11265 // the same size. Instead of casting the pointer before the load, cast
11266 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011267 Value *NewLoad =
11268 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011269 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011270 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011271 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011272 }
11273 }
11274 return 0;
11275}
11276
Chris Lattner833b8a42003-06-26 05:06:25 +000011277Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11278 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011279
Dan Gohman9941f742007-07-20 16:34:21 +000011280 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011281 if (TD) {
11282 unsigned KnownAlign =
11283 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11284 if (KnownAlign >
11285 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11286 LI.getAlignment()))
11287 LI.setAlignment(KnownAlign);
11288 }
Dan Gohman9941f742007-07-20 16:34:21 +000011289
Chris Lattner963f4ba2009-08-30 20:36:46 +000011290 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011291 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011292 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011293 return Res;
11294
11295 // None of the following transforms are legal for volatile loads.
11296 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011297
Dan Gohman2276a7b2008-10-15 23:19:35 +000011298 // Do really simple store-to-load forwarding and load CSE, to catch cases
11299 // where there are several consequtive memory accesses to the same location,
11300 // separated by a few arithmetic operations.
11301 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011302 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11303 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011304
Christopher Lambb15147e2007-12-29 07:56:53 +000011305 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11306 const Value *GEPI0 = GEPI->getOperand(0);
11307 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011308 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011309 // Insert a new store to null instruction before the load to indicate
11310 // that this code is not reachable. We do this instead of inserting
11311 // an unreachable instruction directly because we cannot modify the
11312 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011313 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011314 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011315 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011316 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011317 }
Chris Lattner37366c12005-05-01 04:24:53 +000011318
Chris Lattnere87597f2004-10-16 18:11:37 +000011319 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011320 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011321 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011322 if (isa<UndefValue>(C) ||
11323 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011324 // Insert a new store to null instruction before the load to indicate that
11325 // this code is not reachable. We do this instead of inserting an
11326 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011327 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011328 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011329 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011330 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011331
Chris Lattnere87597f2004-10-16 18:11:37 +000011332 // Instcombine load (constant global) into the value loaded.
11333 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011334 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011335 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011336
Chris Lattnere87597f2004-10-16 18:11:37 +000011337 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011338 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011339 if (CE->getOpcode() == Instruction::GetElementPtr) {
11340 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011341 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011342 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011343 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011344 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011345 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011346 if (CE->getOperand(0)->isNullValue()) {
11347 // Insert a new store to null instruction before the load to indicate
11348 // that this code is not reachable. We do this instead of inserting
11349 // an unreachable instruction directly because we cannot modify the
11350 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011351 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011352 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011353 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011354 }
11355
Reid Spencer3da59db2006-11-27 01:05:10 +000011356 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011357 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011358 return Res;
11359 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011360 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011361 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011362
11363 // If this load comes from anywhere in a constant global, and if the global
11364 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011365 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011366 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011367 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011368 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011369 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011370 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011371 }
11372 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011373
Chris Lattner37366c12005-05-01 04:24:53 +000011374 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011375 // Change select and PHI nodes to select values instead of addresses: this
11376 // helps alias analysis out a lot, allows many others simplifications, and
11377 // exposes redundancy in the code.
11378 //
11379 // Note that we cannot do the transformation unless we know that the
11380 // introduced loads cannot trap! Something like this is valid as long as
11381 // the condition is always false: load (select bool %C, int* null, int* %G),
11382 // but it would not be valid if we transformed it to load from null
11383 // unconditionally.
11384 //
11385 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11386 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011387 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11388 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011389 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11390 SI->getOperand(1)->getName()+".val");
11391 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11392 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011393 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011394 }
11395
Chris Lattner684fe212004-09-23 15:46:00 +000011396 // load (select (cond, null, P)) -> load P
11397 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11398 if (C->isNullValue()) {
11399 LI.setOperand(0, SI->getOperand(2));
11400 return &LI;
11401 }
11402
11403 // load (select (cond, P, null)) -> load P
11404 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11405 if (C->isNullValue()) {
11406 LI.setOperand(0, SI->getOperand(1));
11407 return &LI;
11408 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011409 }
11410 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011411 return 0;
11412}
11413
Reid Spencer55af2b52007-01-19 21:20:31 +000011414/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011415/// when possible. This makes it generally easy to do alias analysis and/or
11416/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011417static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11418 User *CI = cast<User>(SI.getOperand(1));
11419 Value *CastOp = CI->getOperand(0);
11420
11421 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011422 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11423 if (SrcTy == 0) return 0;
11424
11425 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011426
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011427 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11428 return 0;
11429
Chris Lattner3914f722009-01-24 01:00:13 +000011430 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11431 /// to its first element. This allows us to handle things like:
11432 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11433 /// on 32-bit hosts.
11434 SmallVector<Value*, 4> NewGEPIndices;
11435
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011436 // If the source is an array, the code below will not succeed. Check to
11437 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11438 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011439 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11440 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011441 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011442 NewGEPIndices.push_back(Zero);
11443
11444 while (1) {
11445 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011446 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011447 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011448 NewGEPIndices.push_back(Zero);
11449 SrcPTy = STy->getElementType(0);
11450 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11451 NewGEPIndices.push_back(Zero);
11452 SrcPTy = ATy->getElementType();
11453 } else {
11454 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011455 }
Chris Lattner3914f722009-01-24 01:00:13 +000011456 }
11457
Owen Andersondebcb012009-07-29 22:17:13 +000011458 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011459 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011460
11461 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11462 return 0;
11463
Chris Lattner71759c42009-01-16 20:12:52 +000011464 // If the pointers point into different address spaces or if they point to
11465 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011466 if (!IC.getTargetData() ||
11467 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011468 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011469 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11470 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011471 return 0;
11472
11473 // Okay, we are casting from one integer or pointer type to another of
11474 // the same size. Instead of casting the pointer before
11475 // the store, cast the value to be stored.
11476 Value *NewCast;
11477 Value *SIOp0 = SI.getOperand(0);
11478 Instruction::CastOps opcode = Instruction::BitCast;
11479 const Type* CastSrcTy = SIOp0->getType();
11480 const Type* CastDstTy = SrcPTy;
11481 if (isa<PointerType>(CastDstTy)) {
11482 if (CastSrcTy->isInteger())
11483 opcode = Instruction::IntToPtr;
11484 } else if (isa<IntegerType>(CastDstTy)) {
11485 if (isa<PointerType>(SIOp0->getType()))
11486 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011487 }
Chris Lattner3914f722009-01-24 01:00:13 +000011488
11489 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11490 // emit a GEP to index into its first field.
11491 if (!NewGEPIndices.empty()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011492 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11493 NewGEPIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011494 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011495 }
11496
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011497 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11498 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011499 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011500}
11501
Chris Lattner4aebaee2008-11-27 08:56:30 +000011502/// equivalentAddressValues - Test if A and B will obviously have the same
11503/// value. This includes recognizing that %t0 and %t1 will have the same
11504/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011505/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011506/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011507/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011508/// %t2 = load i32* %t1
11509///
11510static bool equivalentAddressValues(Value *A, Value *B) {
11511 // Test if the values are trivially equivalent.
11512 if (A == B) return true;
11513
11514 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011515 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11516 // its only used to compare two uses within the same basic block, which
11517 // means that they'll always either have the same value or one of them
11518 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011519 if (isa<BinaryOperator>(A) ||
11520 isa<CastInst>(A) ||
11521 isa<PHINode>(A) ||
11522 isa<GetElementPtrInst>(A))
11523 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011524 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011525 return true;
11526
11527 // Otherwise they may not be equivalent.
11528 return false;
11529}
11530
Dale Johannesen4945c652009-03-03 21:26:39 +000011531// If this instruction has two uses, one of which is a llvm.dbg.declare,
11532// return the llvm.dbg.declare.
11533DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11534 if (!V->hasNUses(2))
11535 return 0;
11536 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11537 UI != E; ++UI) {
11538 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11539 return DI;
11540 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11541 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11542 return DI;
11543 }
11544 }
11545 return 0;
11546}
11547
Chris Lattner2f503e62005-01-31 05:36:43 +000011548Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11549 Value *Val = SI.getOperand(0);
11550 Value *Ptr = SI.getOperand(1);
11551
11552 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011553 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011554 ++NumCombined;
11555 return 0;
11556 }
Chris Lattner836692d2007-01-15 06:51:56 +000011557
11558 // If the RHS is an alloca with a single use, zapify the store, making the
11559 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011560 // If the RHS is an alloca with a two uses, the other one being a
11561 // llvm.dbg.declare, zapify the store and the declare, making the
11562 // alloca dead. We must do this to prevent declare's from affecting
11563 // codegen.
11564 if (!SI.isVolatile()) {
11565 if (Ptr->hasOneUse()) {
11566 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011567 EraseInstFromFunction(SI);
11568 ++NumCombined;
11569 return 0;
11570 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011571 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11572 if (isa<AllocaInst>(GEP->getOperand(0))) {
11573 if (GEP->getOperand(0)->hasOneUse()) {
11574 EraseInstFromFunction(SI);
11575 ++NumCombined;
11576 return 0;
11577 }
11578 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11579 EraseInstFromFunction(*DI);
11580 EraseInstFromFunction(SI);
11581 ++NumCombined;
11582 return 0;
11583 }
11584 }
11585 }
11586 }
11587 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11588 EraseInstFromFunction(*DI);
11589 EraseInstFromFunction(SI);
11590 ++NumCombined;
11591 return 0;
11592 }
Chris Lattner836692d2007-01-15 06:51:56 +000011593 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011594
Dan Gohman9941f742007-07-20 16:34:21 +000011595 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011596 if (TD) {
11597 unsigned KnownAlign =
11598 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11599 if (KnownAlign >
11600 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11601 SI.getAlignment()))
11602 SI.setAlignment(KnownAlign);
11603 }
Dan Gohman9941f742007-07-20 16:34:21 +000011604
Dale Johannesenacb51a32009-03-03 01:43:03 +000011605 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011606 // stores to the same location, separated by a few arithmetic operations. This
11607 // situation often occurs with bitfield accesses.
11608 BasicBlock::iterator BBI = &SI;
11609 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11610 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011611 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011612 // Don't count debug info directives, lest they affect codegen,
11613 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11614 // It is necessary for correctness to skip those that feed into a
11615 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011616 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011617 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011618 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011619 continue;
11620 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011621
11622 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11623 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011624 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11625 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011626 ++NumDeadStore;
11627 ++BBI;
11628 EraseInstFromFunction(*PrevSI);
11629 continue;
11630 }
11631 break;
11632 }
11633
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011634 // If this is a load, we have to stop. However, if the loaded value is from
11635 // the pointer we're loading and is producing the pointer we're storing,
11636 // then *this* store is dead (X = load P; store X -> P).
11637 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011638 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11639 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011640 EraseInstFromFunction(SI);
11641 ++NumCombined;
11642 return 0;
11643 }
11644 // Otherwise, this is a load from some other location. Stores before it
11645 // may not be dead.
11646 break;
11647 }
11648
Chris Lattner9ca96412006-02-08 03:25:32 +000011649 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011650 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011651 break;
11652 }
11653
11654
11655 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011656
11657 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011658 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011659 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011660 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011661 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011662 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011663 ++NumCombined;
11664 }
11665 return 0; // Do not modify these!
11666 }
11667
11668 // store undef, Ptr -> noop
11669 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011670 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011671 ++NumCombined;
11672 return 0;
11673 }
11674
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011675 // If the pointer destination is a cast, see if we can fold the cast into the
11676 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011677 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011678 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11679 return Res;
11680 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011681 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011682 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11683 return Res;
11684
Chris Lattner408902b2005-09-12 23:23:25 +000011685
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011686 // If this store is the last instruction in the basic block (possibly
11687 // excepting debug info instructions and the pointer bitcasts that feed
11688 // into them), and if the block ends with an unconditional branch, try
11689 // to move it to the successor block.
11690 BBI = &SI;
11691 do {
11692 ++BBI;
11693 } while (isa<DbgInfoIntrinsic>(BBI) ||
11694 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011695 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011696 if (BI->isUnconditional())
11697 if (SimplifyStoreAtEndOfBlock(SI))
11698 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011699
Chris Lattner2f503e62005-01-31 05:36:43 +000011700 return 0;
11701}
11702
Chris Lattner3284d1f2007-04-15 00:07:55 +000011703/// SimplifyStoreAtEndOfBlock - Turn things like:
11704/// if () { *P = v1; } else { *P = v2 }
11705/// into a phi node with a store in the successor.
11706///
Chris Lattner31755a02007-04-15 01:02:18 +000011707/// Simplify things like:
11708/// *P = v1; if () { *P = v2; }
11709/// into a phi node with a store in the successor.
11710///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011711bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11712 BasicBlock *StoreBB = SI.getParent();
11713
11714 // Check to see if the successor block has exactly two incoming edges. If
11715 // so, see if the other predecessor contains a store to the same location.
11716 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011717 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011718
11719 // Determine whether Dest has exactly two predecessors and, if so, compute
11720 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011721 pred_iterator PI = pred_begin(DestBB);
11722 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011723 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011724 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011725 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011726 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011727 return false;
11728
11729 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011730 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011731 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011732 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011733 }
Chris Lattner31755a02007-04-15 01:02:18 +000011734 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011735 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011736
11737 // Bail out if all the relevant blocks aren't distinct (this can happen,
11738 // for example, if SI is in an infinite loop)
11739 if (StoreBB == DestBB || OtherBB == DestBB)
11740 return false;
11741
Chris Lattner31755a02007-04-15 01:02:18 +000011742 // Verify that the other block ends in a branch and is not otherwise empty.
11743 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011744 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011745 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011746 return false;
11747
Chris Lattner31755a02007-04-15 01:02:18 +000011748 // If the other block ends in an unconditional branch, check for the 'if then
11749 // else' case. there is an instruction before the branch.
11750 StoreInst *OtherStore = 0;
11751 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011752 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011753 // Skip over debugging info.
11754 while (isa<DbgInfoIntrinsic>(BBI) ||
11755 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11756 if (BBI==OtherBB->begin())
11757 return false;
11758 --BBI;
11759 }
11760 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011761 OtherStore = dyn_cast<StoreInst>(BBI);
11762 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11763 return false;
11764 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011765 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011766 // destinations is StoreBB, then we have the if/then case.
11767 if (OtherBr->getSuccessor(0) != StoreBB &&
11768 OtherBr->getSuccessor(1) != StoreBB)
11769 return false;
11770
11771 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011772 // if/then triangle. See if there is a store to the same ptr as SI that
11773 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011774 for (;; --BBI) {
11775 // Check to see if we find the matching store.
11776 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11777 if (OtherStore->getOperand(1) != SI.getOperand(1))
11778 return false;
11779 break;
11780 }
Eli Friedman6903a242008-06-13 22:02:12 +000011781 // If we find something that may be using or overwriting the stored
11782 // value, or if we run out of instructions, we can't do the xform.
11783 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011784 BBI == OtherBB->begin())
11785 return false;
11786 }
11787
11788 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011789 // make sure nothing reads or overwrites the stored value in
11790 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011791 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11792 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011793 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011794 return false;
11795 }
11796 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011797
Chris Lattner31755a02007-04-15 01:02:18 +000011798 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011799 Value *MergedVal = OtherStore->getOperand(0);
11800 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011801 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011802 PN->reserveOperandSpace(2);
11803 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011804 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11805 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011806 }
11807
11808 // Advance to a place where it is safe to insert the new store and
11809 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011810 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011811 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11812 OtherStore->isVolatile()), *BBI);
11813
11814 // Nuke the old stores.
11815 EraseInstFromFunction(SI);
11816 EraseInstFromFunction(*OtherStore);
11817 ++NumCombined;
11818 return true;
11819}
11820
Chris Lattner2f503e62005-01-31 05:36:43 +000011821
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011822Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11823 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011824 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011825 BasicBlock *TrueDest;
11826 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011827 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011828 !isa<Constant>(X)) {
11829 // Swap Destinations and condition...
11830 BI.setCondition(X);
11831 BI.setSuccessor(0, FalseDest);
11832 BI.setSuccessor(1, TrueDest);
11833 return &BI;
11834 }
11835
Reid Spencere4d87aa2006-12-23 06:05:41 +000011836 // Cannonicalize fcmp_one -> fcmp_oeq
11837 FCmpInst::Predicate FPred; Value *Y;
11838 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011839 TrueDest, FalseDest)) &&
11840 BI.getCondition()->hasOneUse())
11841 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11842 FPred == FCmpInst::FCMP_OGE) {
11843 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11844 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11845
11846 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011847 BI.setSuccessor(0, FalseDest);
11848 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011849 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011850 return &BI;
11851 }
11852
11853 // Cannonicalize icmp_ne -> icmp_eq
11854 ICmpInst::Predicate IPred;
11855 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011856 TrueDest, FalseDest)) &&
11857 BI.getCondition()->hasOneUse())
11858 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11859 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11860 IPred == ICmpInst::ICMP_SGE) {
11861 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11862 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11863 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011864 BI.setSuccessor(0, FalseDest);
11865 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011866 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011867 return &BI;
11868 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011869
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011870 return 0;
11871}
Chris Lattner0864acf2002-11-04 16:18:53 +000011872
Chris Lattner46238a62004-07-03 00:26:11 +000011873Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11874 Value *Cond = SI.getCondition();
11875 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11876 if (I->getOpcode() == Instruction::Add)
11877 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11878 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11879 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011880 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011881 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011882 AddRHS));
11883 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011884 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011885 return &SI;
11886 }
11887 }
11888 return 0;
11889}
11890
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011891Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011892 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011893
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011894 if (!EV.hasIndices())
11895 return ReplaceInstUsesWith(EV, Agg);
11896
11897 if (Constant *C = dyn_cast<Constant>(Agg)) {
11898 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011899 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011900
11901 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011902 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011903
11904 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11905 // Extract the element indexed by the first index out of the constant
11906 Value *V = C->getOperand(*EV.idx_begin());
11907 if (EV.getNumIndices() > 1)
11908 // Extract the remaining indices out of the constant indexed by the
11909 // first index
11910 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11911 else
11912 return ReplaceInstUsesWith(EV, V);
11913 }
11914 return 0; // Can't handle other constants
11915 }
11916 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11917 // We're extracting from an insertvalue instruction, compare the indices
11918 const unsigned *exti, *exte, *insi, *inse;
11919 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11920 exte = EV.idx_end(), inse = IV->idx_end();
11921 exti != exte && insi != inse;
11922 ++exti, ++insi) {
11923 if (*insi != *exti)
11924 // The insert and extract both reference distinctly different elements.
11925 // This means the extract is not influenced by the insert, and we can
11926 // replace the aggregate operand of the extract with the aggregate
11927 // operand of the insert. i.e., replace
11928 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11929 // %E = extractvalue { i32, { i32 } } %I, 0
11930 // with
11931 // %E = extractvalue { i32, { i32 } } %A, 0
11932 return ExtractValueInst::Create(IV->getAggregateOperand(),
11933 EV.idx_begin(), EV.idx_end());
11934 }
11935 if (exti == exte && insi == inse)
11936 // Both iterators are at the end: Index lists are identical. Replace
11937 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11938 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11939 // with "i32 42"
11940 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11941 if (exti == exte) {
11942 // The extract list is a prefix of the insert list. i.e. replace
11943 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11944 // %E = extractvalue { i32, { i32 } } %I, 1
11945 // with
11946 // %X = extractvalue { i32, { i32 } } %A, 1
11947 // %E = insertvalue { i32 } %X, i32 42, 0
11948 // by switching the order of the insert and extract (though the
11949 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011950 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11951 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011952 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11953 insi, inse);
11954 }
11955 if (insi == inse)
11956 // The insert list is a prefix of the extract list
11957 // We can simply remove the common indices from the extract and make it
11958 // operate on the inserted value instead of the insertvalue result.
11959 // i.e., replace
11960 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11961 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11962 // with
11963 // %E extractvalue { i32 } { i32 42 }, 0
11964 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11965 exti, exte);
11966 }
11967 // Can't simplify extracts from other values. Note that nested extracts are
11968 // already simplified implicitely by the above (extract ( extract (insert) )
11969 // will be translated into extract ( insert ( extract ) ) first and then just
11970 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011971 return 0;
11972}
11973
Chris Lattner220b0cf2006-03-05 00:22:33 +000011974/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11975/// is to leave as a vector operation.
11976static bool CheapToScalarize(Value *V, bool isConstant) {
11977 if (isa<ConstantAggregateZero>(V))
11978 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011979 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011980 if (isConstant) return true;
11981 // If all elts are the same, we can extract.
11982 Constant *Op0 = C->getOperand(0);
11983 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11984 if (C->getOperand(i) != Op0)
11985 return false;
11986 return true;
11987 }
11988 Instruction *I = dyn_cast<Instruction>(V);
11989 if (!I) return false;
11990
11991 // Insert element gets simplified to the inserted element or is deleted if
11992 // this is constant idx extract element and its a constant idx insertelt.
11993 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11994 isa<ConstantInt>(I->getOperand(2)))
11995 return true;
11996 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11997 return true;
11998 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11999 if (BO->hasOneUse() &&
12000 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12001 CheapToScalarize(BO->getOperand(1), isConstant)))
12002 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012003 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12004 if (CI->hasOneUse() &&
12005 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12006 CheapToScalarize(CI->getOperand(1), isConstant)))
12007 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012008
12009 return false;
12010}
12011
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012012/// Read and decode a shufflevector mask.
12013///
12014/// It turns undef elements into values that are larger than the number of
12015/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012016static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12017 unsigned NElts = SVI->getType()->getNumElements();
12018 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12019 return std::vector<unsigned>(NElts, 0);
12020 if (isa<UndefValue>(SVI->getOperand(2)))
12021 return std::vector<unsigned>(NElts, 2*NElts);
12022
12023 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012024 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012025 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12026 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012027 Result.push_back(NElts*2); // undef -> 8
12028 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012029 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012030 return Result;
12031}
12032
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012033/// FindScalarElement - Given a vector and an element number, see if the scalar
12034/// value is already around as a register, for example if it were inserted then
12035/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012036static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012037 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012038 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12039 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012040 unsigned Width = PTy->getNumElements();
12041 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012042 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012043
12044 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012045 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012046 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012047 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012048 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012049 return CP->getOperand(EltNo);
12050 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12051 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012052 if (!isa<ConstantInt>(III->getOperand(2)))
12053 return 0;
12054 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012055
12056 // If this is an insert to the element we are looking for, return the
12057 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012058 if (EltNo == IIElt)
12059 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012060
12061 // Otherwise, the insertelement doesn't modify the value, recurse on its
12062 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012063 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012064 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012065 unsigned LHSWidth =
12066 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012067 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012068 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012069 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012070 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012071 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012072 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012073 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012074 }
12075
12076 // Otherwise, we don't know.
12077 return 0;
12078}
12079
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012080Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012081 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012082 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012083 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012084
Dan Gohman07a96762007-07-16 14:29:03 +000012085 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012086 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012087 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012088
Reid Spencer9d6565a2007-02-15 02:26:10 +000012089 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012090 // If vector val is constant with all elements the same, replace EI with
12091 // that element. When the elements are not identical, we cannot replace yet
12092 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012093 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012094 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012095 if (C->getOperand(i) != op0) {
12096 op0 = 0;
12097 break;
12098 }
12099 if (op0)
12100 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012101 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012102
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012103 // If extracting a specified index from the vector, see if we can recursively
12104 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012105 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012106 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012107 unsigned VectorWidth =
12108 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012109
12110 // If this is extracting an invalid index, turn this into undef, to avoid
12111 // crashing the code below.
12112 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012113 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012114
Chris Lattner867b99f2006-10-05 06:55:50 +000012115 // This instruction only demands the single element from the input vector.
12116 // If the input vector has a single use, simplify it based on this use
12117 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012118 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012119 APInt UndefElts(VectorWidth, 0);
12120 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012121 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012122 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012123 EI.setOperand(0, V);
12124 return &EI;
12125 }
12126 }
12127
Owen Andersond672ecb2009-07-03 00:17:18 +000012128 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012129 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012130
12131 // If the this extractelement is directly using a bitcast from a vector of
12132 // the same number of elements, see if we can find the source element from
12133 // it. In this case, we will end up needing to bitcast the scalars.
12134 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12135 if (const VectorType *VT =
12136 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12137 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012138 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12139 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012140 return new BitCastInst(Elt, EI.getType());
12141 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012142 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012143
Chris Lattner73fa49d2006-05-25 22:53:38 +000012144 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012145 if (I->hasOneUse()) {
12146 // Push extractelement into predecessor operation if legal and
12147 // profitable to do so
12148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012149 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12150 if (CheapToScalarize(BO, isConstantElt)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012151 Value *newEI0 =
12152 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12153 EI.getName()+".lhs");
12154 Value *newEI1 =
12155 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12156 EI.getName()+".rhs");
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012157 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012158 }
Chris Lattner08142f22009-08-30 19:47:22 +000012159 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12160 unsigned AS = LI->getPointerAddressSpace();
12161 Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12162 PointerType::get(EI.getType(), AS),
12163 I->getOperand(0)->getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012164 Value *GEP =
12165 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012166 cast<GEPOperator>(GEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012167
12168 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12169
12170 // Make sure the Load goes before the load instruction in the source,
12171 // not wherever the extract happens to be.
Chris Lattner08142f22009-08-30 19:47:22 +000012172 if (Instruction *P = dyn_cast<Instruction>(Ptr))
12173 P->moveBefore(I);
12174 if (Instruction *G = dyn_cast<Instruction>(GEP))
12175 G->moveBefore(I);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012176 Load->moveBefore(I);
12177
Mon P Wang7c4efa62009-08-13 05:12:13 +000012178 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012179 }
12180 }
12181 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12182 // Extracting the inserted element?
12183 if (IE->getOperand(2) == EI.getOperand(1))
12184 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12185 // If the inserted and extracted elements are constants, they must not
12186 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012187 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012188 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012189 EI.setOperand(0, IE->getOperand(0));
12190 return &EI;
12191 }
12192 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12193 // If this is extracting an element from a shufflevector, figure out where
12194 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012195 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12196 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012197 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012198 unsigned LHSWidth =
12199 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12200
12201 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012202 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012203 else if (SrcIdx < LHSWidth*2) {
12204 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012205 Src = SVI->getOperand(1);
12206 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012207 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012208 }
Eric Christophera3500da2009-07-25 02:28:41 +000012209 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012210 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12211 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012212 }
12213 }
Eli Friedman2451a642009-07-18 23:06:53 +000012214 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012215 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012216 return 0;
12217}
12218
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012219/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12220/// elements from either LHS or RHS, return the shuffle mask and true.
12221/// Otherwise, return false.
12222static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012223 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012224 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012225 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12226 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012227 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012228
12229 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012230 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012231 return true;
12232 } else if (V == LHS) {
12233 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012234 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012235 return true;
12236 } else if (V == RHS) {
12237 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012238 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012239 return true;
12240 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12241 // If this is an insert of an extract from some other vector, include it.
12242 Value *VecOp = IEI->getOperand(0);
12243 Value *ScalarOp = IEI->getOperand(1);
12244 Value *IdxOp = IEI->getOperand(2);
12245
Chris Lattnerd929f062006-04-27 21:14:21 +000012246 if (!isa<ConstantInt>(IdxOp))
12247 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012248 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012249
12250 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12251 // Okay, we can handle this if the vector we are insertinting into is
12252 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012253 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012254 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012255 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012256 return true;
12257 }
12258 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12259 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012260 EI->getOperand(0)->getType() == V->getType()) {
12261 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012262 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012263
12264 // This must be extracting from either LHS or RHS.
12265 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12266 // Okay, we can handle this if the vector we are insertinting into is
12267 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012268 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012269 // If so, update the mask to reflect the inserted value.
12270 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012271 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012272 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012273 } else {
12274 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012275 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012276 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012277
12278 }
12279 return true;
12280 }
12281 }
12282 }
12283 }
12284 }
12285 // TODO: Handle shufflevector here!
12286
12287 return false;
12288}
12289
12290/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12291/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12292/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012293static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012294 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012295 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012296 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012297 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012298 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012299
12300 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012301 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012302 return V;
12303 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012304 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012305 return V;
12306 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12307 // If this is an insert of an extract from some other vector, include it.
12308 Value *VecOp = IEI->getOperand(0);
12309 Value *ScalarOp = IEI->getOperand(1);
12310 Value *IdxOp = IEI->getOperand(2);
12311
12312 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12313 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12314 EI->getOperand(0)->getType() == V->getType()) {
12315 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012316 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12317 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012318
12319 // Either the extracted from or inserted into vector must be RHSVec,
12320 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012321 if (EI->getOperand(0) == RHS || RHS == 0) {
12322 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012323 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012324 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012325 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012326 return V;
12327 }
12328
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012329 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012330 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12331 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012332 // Everything but the extracted element is replaced with the RHS.
12333 for (unsigned i = 0; i != NumElts; ++i) {
12334 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012335 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012336 }
12337 return V;
12338 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012339
12340 // If this insertelement is a chain that comes from exactly these two
12341 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012342 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12343 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012344 return EI->getOperand(0);
12345
Chris Lattnerefb47352006-04-15 01:39:45 +000012346 }
12347 }
12348 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012349 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012350
12351 // Otherwise, can't do anything fancy. Return an identity vector.
12352 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012353 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012354 return V;
12355}
12356
12357Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12358 Value *VecOp = IE.getOperand(0);
12359 Value *ScalarOp = IE.getOperand(1);
12360 Value *IdxOp = IE.getOperand(2);
12361
Chris Lattner599ded12007-04-09 01:11:16 +000012362 // Inserting an undef or into an undefined place, remove this.
12363 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12364 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012365
Chris Lattnerefb47352006-04-15 01:39:45 +000012366 // If the inserted element was extracted from some other vector, and if the
12367 // indexes are constant, try to turn this into a shufflevector operation.
12368 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12369 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12370 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012371 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012372 unsigned ExtractedIdx =
12373 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012374 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012375
12376 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12377 return ReplaceInstUsesWith(IE, VecOp);
12378
12379 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012380 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012381
12382 // If we are extracting a value from a vector, then inserting it right
12383 // back into the same place, just use the input vector.
12384 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12385 return ReplaceInstUsesWith(IE, VecOp);
12386
12387 // We could theoretically do this for ANY input. However, doing so could
12388 // turn chains of insertelement instructions into a chain of shufflevector
12389 // instructions, and right now we do not merge shufflevectors. As such,
12390 // only do this in a situation where it is clear that there is benefit.
12391 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12392 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12393 // the values of VecOp, except then one read from EIOp0.
12394 // Build a new shuffle mask.
12395 std::vector<Constant*> Mask;
12396 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012397 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012398 else {
12399 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012400 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012401 NumVectorElts));
12402 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012403 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012404 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012405 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012406 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012407 }
12408
12409 // If this insertelement isn't used by some other insertelement, turn it
12410 // (and any insertelements it points to), into one big shuffle.
12411 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12412 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012413 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012414 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012415 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012416 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012417 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012418 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012419 }
12420 }
12421 }
12422
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012423 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12424 APInt UndefElts(VWidth, 0);
12425 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12426 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12427 return &IE;
12428
Chris Lattnerefb47352006-04-15 01:39:45 +000012429 return 0;
12430}
12431
12432
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012433Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12434 Value *LHS = SVI.getOperand(0);
12435 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012436 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012437
12438 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012439
Chris Lattner867b99f2006-10-05 06:55:50 +000012440 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012441 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012442 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012443
Dan Gohman488fbfc2008-09-09 18:11:14 +000012444 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012445
12446 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12447 return 0;
12448
Evan Cheng388df622009-02-03 10:05:09 +000012449 APInt UndefElts(VWidth, 0);
12450 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12451 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012452 LHS = SVI.getOperand(0);
12453 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012454 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012455 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012456
Chris Lattner863bcff2006-05-25 23:48:38 +000012457 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12458 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12459 if (LHS == RHS || isa<UndefValue>(LHS)) {
12460 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012461 // shuffle(undef,undef,mask) -> undef.
12462 return ReplaceInstUsesWith(SVI, LHS);
12463 }
12464
Chris Lattner863bcff2006-05-25 23:48:38 +000012465 // Remap any references to RHS to use LHS.
12466 std::vector<Constant*> Elts;
12467 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012468 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012469 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012470 else {
12471 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012472 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012473 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012474 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012475 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012476 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012477 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012478 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012479 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012480 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012481 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012482 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012483 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012484 LHS = SVI.getOperand(0);
12485 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012486 MadeChange = true;
12487 }
12488
Chris Lattner7b2e27922006-05-26 00:29:06 +000012489 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012490 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012491
Chris Lattner863bcff2006-05-25 23:48:38 +000012492 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12493 if (Mask[i] >= e*2) continue; // Ignore undef values.
12494 // Is this an identity shuffle of the LHS value?
12495 isLHSID &= (Mask[i] == i);
12496
12497 // Is this an identity shuffle of the RHS value?
12498 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012499 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012500
Chris Lattner863bcff2006-05-25 23:48:38 +000012501 // Eliminate identity shuffles.
12502 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12503 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012504
Chris Lattner7b2e27922006-05-26 00:29:06 +000012505 // If the LHS is a shufflevector itself, see if we can combine it with this
12506 // one without producing an unusual shuffle. Here we are really conservative:
12507 // we are absolutely afraid of producing a shuffle mask not in the input
12508 // program, because the code gen may not be smart enough to turn a merged
12509 // shuffle into two specific shuffles: it may produce worse code. As such,
12510 // we only merge two shuffles if the result is one of the two input shuffle
12511 // masks. In this case, merging the shuffles just removes one instruction,
12512 // which we know is safe. This is good for things like turning:
12513 // (splat(splat)) -> splat.
12514 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12515 if (isa<UndefValue>(RHS)) {
12516 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12517
12518 std::vector<unsigned> NewMask;
12519 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12520 if (Mask[i] >= 2*e)
12521 NewMask.push_back(2*e);
12522 else
12523 NewMask.push_back(LHSMask[Mask[i]]);
12524
12525 // If the result mask is equal to the src shuffle or this shuffle mask, do
12526 // the replacement.
12527 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012528 unsigned LHSInNElts =
12529 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012530 std::vector<Constant*> Elts;
12531 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012532 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012533 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012534 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012535 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012536 }
12537 }
12538 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12539 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012540 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012541 }
12542 }
12543 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012544
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012545 return MadeChange ? &SVI : 0;
12546}
12547
12548
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012549
Chris Lattnerea1c4542004-12-08 23:43:58 +000012550
12551/// TryToSinkInstruction - Try to move the specified instruction from its
12552/// current block into the beginning of DestBlock, which can only happen if it's
12553/// safe to move the instruction past all of the instructions between it and the
12554/// end of its block.
12555static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12556 assert(I->hasOneUse() && "Invariants didn't hold!");
12557
Chris Lattner108e9022005-10-27 17:13:11 +000012558 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012559 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012560 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012561
Chris Lattnerea1c4542004-12-08 23:43:58 +000012562 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012563 if (isa<AllocaInst>(I) && I->getParent() ==
12564 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012565 return false;
12566
Chris Lattner96a52a62004-12-09 07:14:34 +000012567 // We can only sink load instructions if there is nothing between the load and
12568 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012569 if (I->mayReadFromMemory()) {
12570 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012571 Scan != E; ++Scan)
12572 if (Scan->mayWriteToMemory())
12573 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012574 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012575
Dan Gohman02dea8b2008-05-23 21:05:58 +000012576 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012577
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012578 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012579 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012580 ++NumSunkInst;
12581 return true;
12582}
12583
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012584
12585/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12586/// all reachable code to the worklist.
12587///
12588/// This has a couple of tricks to make the code faster and more powerful. In
12589/// particular, we constant fold and DCE instructions as we go, to avoid adding
12590/// them to the worklist (this significantly speeds up instcombine on code where
12591/// many instructions are dead or constant). Additionally, if we find a branch
12592/// whose condition is a known constant, we only visit the reachable successors.
12593///
12594static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012595 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012596 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012597 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012598 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012599 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012600
Chris Lattner2c7718a2007-03-23 19:17:18 +000012601 while (!Worklist.empty()) {
12602 BB = Worklist.back();
12603 Worklist.pop_back();
12604
12605 // We have now visited this block! If we've already been here, ignore it.
12606 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012607
12608 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012609 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12610 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012611
Chris Lattner2c7718a2007-03-23 19:17:18 +000012612 // DCE instruction if trivially dead.
12613 if (isInstructionTriviallyDead(Inst)) {
12614 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012615 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012616 Inst->eraseFromParent();
12617 continue;
12618 }
12619
12620 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012621 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012622 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12623 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012624 Inst->replaceAllUsesWith(C);
12625 ++NumConstProp;
12626 Inst->eraseFromParent();
12627 continue;
12628 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012629
Devang Patel7fe1dec2008-11-19 18:56:50 +000012630 // If there are two consecutive llvm.dbg.stoppoint calls then
12631 // it is likely that the optimizer deleted code in between these
12632 // two intrinsics.
12633 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12634 if (DBI_Next) {
12635 if (DBI_Prev
12636 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12637 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012638 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012639 DBI_Prev->eraseFromParent();
12640 }
12641 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012642 } else {
12643 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012644 }
12645
Chris Lattner7a1e9242009-08-30 06:13:40 +000012646 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012647 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012648
12649 // Recursively visit successors. If this is a branch or switch on a
12650 // constant, only visit the reachable successor.
12651 TerminatorInst *TI = BB->getTerminator();
12652 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12653 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12654 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012655 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012656 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012657 continue;
12658 }
12659 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12660 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12661 // See if this is an explicit destination.
12662 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12663 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012664 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012665 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012666 continue;
12667 }
12668
12669 // Otherwise it is the default destination.
12670 Worklist.push_back(SI->getSuccessor(0));
12671 continue;
12672 }
12673 }
12674
12675 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12676 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012677 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012678}
12679
Chris Lattnerec9c3582007-03-03 02:04:50 +000012680bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012681 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012682 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012683
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012684 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12685 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012686
Chris Lattnerb3d59702005-07-07 20:40:38 +000012687 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012688 // Do a depth-first traversal of the function, populate the worklist with
12689 // the reachable instructions. Ignore blocks that are not reachable. Keep
12690 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012691 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012692 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012693
Chris Lattnerb3d59702005-07-07 20:40:38 +000012694 // Do a quick scan over the function. If we find any blocks that are
12695 // unreachable, remove any instructions inside of them. This prevents
12696 // the instcombine code from having to deal with some bad special cases.
12697 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12698 if (!Visited.count(BB)) {
12699 Instruction *Term = BB->getTerminator();
12700 while (Term != BB->begin()) { // Remove instrs bottom-up
12701 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012702
Chris Lattnerbdff5482009-08-23 04:37:46 +000012703 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012704 // A debug intrinsic shouldn't force another iteration if we weren't
12705 // going to do one without it.
12706 if (!isa<DbgInfoIntrinsic>(I)) {
12707 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012708 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012709 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012710 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012711 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012712 I->eraseFromParent();
12713 }
12714 }
12715 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012716
Chris Lattner873ff012009-08-30 05:55:36 +000012717 while (!Worklist.isEmpty()) {
12718 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012719 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012720
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012721 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012722 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012723 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012724 EraseInstFromFunction(*I);
12725 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012726 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012727 continue;
12728 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012729
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012730 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012731 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012732 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012733
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012734 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012735 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012736 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012737 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012738 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012739 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012740 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012741
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012742 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012743 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012744 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12745 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012746 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12747 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012748 if (NewC != CE) {
12749 i->set(NewC);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012750 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012751 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012752 }
12753
Chris Lattnerea1c4542004-12-08 23:43:58 +000012754 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012755 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012756 BasicBlock *BB = I->getParent();
12757 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12758 if (UserParent != BB) {
12759 bool UserIsSuccessor = false;
12760 // See if the user is one of our successors.
12761 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12762 if (*SI == UserParent) {
12763 UserIsSuccessor = true;
12764 break;
12765 }
12766
12767 // If the user is one of our immediate successors, and if that successor
12768 // only has us as a predecessors (we'd have to split the critical edge
12769 // otherwise), we can keep going.
12770 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12771 next(pred_begin(UserParent)) == pred_end(UserParent))
12772 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012773 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012774 }
12775 }
12776
Chris Lattner74381062009-08-30 07:44:24 +000012777 // Now that we have an instruction, try combining it to simplify it.
12778 Builder->SetInsertPoint(I->getParent(), I);
12779
Reid Spencera9b81012007-03-26 17:44:01 +000012780#ifndef NDEBUG
12781 std::string OrigI;
12782#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012783 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012784
Chris Lattner90ac28c2002-08-02 19:29:35 +000012785 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012786 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012787 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012788 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012789 DEBUG(errs() << "IC: Old = " << *I << '\n'
12790 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012791
Chris Lattnerf523d062004-06-09 05:08:07 +000012792 // Everything uses the new instruction now.
12793 I->replaceAllUsesWith(Result);
12794
12795 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012796 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012797 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012798
Chris Lattner6934a042007-02-11 01:23:03 +000012799 // Move the name to the new instruction first.
12800 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012801
12802 // Insert the new instruction into the basic block...
12803 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012804 BasicBlock::iterator InsertPos = I;
12805
12806 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12807 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12808 ++InsertPos;
12809
12810 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012811
Chris Lattner7a1e9242009-08-30 06:13:40 +000012812 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012813 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012814#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012815 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12816 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012817#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012818
Chris Lattner90ac28c2002-08-02 19:29:35 +000012819 // If the instruction was modified, it's possible that it is now dead.
12820 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012821 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012822 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012823 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012824 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012825 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012826 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012827 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012828 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012829 }
12830 }
12831
Chris Lattner873ff012009-08-30 05:55:36 +000012832 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012833 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012834}
12835
Chris Lattnerec9c3582007-03-03 02:04:50 +000012836
12837bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012838 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012839 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012840
Chris Lattner74381062009-08-30 07:44:24 +000012841
12842 /// Builder - This is an IRBuilder that automatically inserts new
12843 /// instructions into the worklist when they are created.
12844 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12845 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12846 InstCombineIRInserter(Worklist));
12847 Builder = &TheBuilder;
12848
Chris Lattnerec9c3582007-03-03 02:04:50 +000012849 bool EverMadeChange = false;
12850
12851 // Iterate while there is work to do.
12852 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012853 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012854 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012855
12856 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012857 return EverMadeChange;
12858}
12859
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012860FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012861 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012862}