blob: 8d61fce4b43bc313632cde2a159fbec261664edc [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez83d63912009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.h"
Chris Lattner173234a2008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000055#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000057#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058#include "llvm/Support/PatternMatch.h"
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) {
Victor Hernandez83d63912009-09-18 22:35:49 +000093 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95 Worklist.push_back(I);
96 }
97
Chris Lattner3c4e38e2009-08-30 06:27:41 +000098 void AddValue(Value *V) {
99 if (Instruction *I = dyn_cast<Instruction>(V))
100 Add(I);
101 }
102
Chris Lattner7a1e9242009-08-30 06:13:40 +0000103 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000104 void Remove(Instruction *I) {
105 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
106 if (It == WorklistMap.end()) return; // Not in worklist.
107
108 // Don't bother moving everything down, just null out the slot.
109 Worklist[It->second] = 0;
110
111 WorklistMap.erase(It);
112 }
113
114 Instruction *RemoveOne() {
115 Instruction *I = Worklist.back();
116 Worklist.pop_back();
117 WorklistMap.erase(I);
118 return I;
119 }
120
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000121 /// AddUsersToWorkList - When an instruction is simplified, add all users of
122 /// the instruction to the work lists because they might get more simplified
123 /// now.
124 ///
125 void AddUsersToWorkList(Instruction &I) {
126 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
127 UI != UE; ++UI)
128 Add(cast<Instruction>(*UI));
129 }
130
Chris Lattner873ff012009-08-30 05:55:36 +0000131
132 /// Zap - check that the worklist is empty and nuke the backing store for
133 /// the map if it is large.
134 void Zap() {
135 assert(WorklistMap.empty() && "Worklist empty, but map not?");
136
137 // Do an explicit clear, this shrinks the map if needed.
138 WorklistMap.clear();
139 }
140 };
141} // end anonymous namespace.
142
143
144namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000145 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
146 /// just like the normal insertion helper, but also adds any new instructions
147 /// to the instcombine worklist.
148 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
149 InstCombineWorklist &Worklist;
150 public:
151 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
152
153 void InsertHelper(Instruction *I, const Twine &Name,
154 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
155 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
156 Worklist.Add(I);
157 }
158 };
159} // end anonymous namespace
160
161
162namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000163 class InstCombiner : 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) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000331 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000332
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)
Chris Lattner9e17b632009-09-02 05:12:37 +00005782 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005783 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005784 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
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
Chris Lattner9e17b632009-09-02 05:12:37 +00005793 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
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
Chris Lattner9e17b632009-09-02 05:12:37 +00005797 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
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
Chris Lattner9e17b632009-09-02 05:12:37 +00005820 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
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)
Chris Lattner9e17b632009-09-02 05:12:37 +00005888 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
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
Chris Lattner9e17b632009-09-02 05:12:37 +00005892 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
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.
Victor Hernandez83d63912009-09-18 22:35:49 +00005896 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || isMalloc(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005897 isa<ConstantPointerNull>(Op0)) &&
Victor Hernandez83d63912009-09-18 22:35:49 +00005898 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || isMalloc(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);
Victor Hernandez83d63912009-09-18 22:35:49 +00006236 return ReplaceInstUsesWith(I,
6237 ConstantInt::get(Type::getInt1Ty(*Context),
6238 !I.isTrueWhenEqual()));
6239 }
6240 break;
6241 case Instruction::Call:
6242 // If we have (malloc != null), and if the malloc has a single use, we
6243 // can assume it is successful and remove the malloc.
6244 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6245 isa<ConstantPointerNull>(RHSC)) {
6246 Worklist.Add(LHSI);
6247 return ReplaceInstUsesWith(I,
6248 ConstantInt::get(Type::getInt1Ty(*Context),
6249 !I.isTrueWhenEqual()));
6250 }
6251 break;
6252 case Instruction::BitCast:
6253 // If we have (malloc != null), and if the malloc has a single use, we
6254 // can assume it is successful and remove the malloc.
6255 CallInst* CI = extractMallocCallFromBitCast(LHSI);
6256 if (CI && CI->hasOneUse() && LHSI->hasOneUse()
6257 && isa<ConstantPointerNull>(RHSC)) {
6258 Worklist.Add(LHSI);
6259 Worklist.Add(CI);
6260 return ReplaceInstUsesWith(I,
6261 ConstantInt::get(Type::getInt1Ty(*Context),
6262 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006263 }
6264 break;
6265 }
Chris Lattner6970b662005-04-23 15:31:55 +00006266 }
6267
Reid Spencere4d87aa2006-12-23 06:05:41 +00006268 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006269 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006270 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006271 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006272 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006273 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6274 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006275 return NI;
6276
Reid Spencere4d87aa2006-12-23 06:05:41 +00006277 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006278 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6279 // now.
6280 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6281 if (isa<PointerType>(Op0->getType()) &&
6282 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006283 // We keep moving the cast from the left operand over to the right
6284 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006285 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006286
Chris Lattner57d86372007-01-06 01:45:59 +00006287 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6288 // so eliminate it as well.
6289 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6290 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006291
Chris Lattnerde90b762003-11-03 04:25:02 +00006292 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006293 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006294 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006295 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006296 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006297 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006298 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006299 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006300 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006301 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006302 }
Chris Lattner57d86372007-01-06 01:45:59 +00006303 }
6304
6305 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006306 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006307 // This comes up when you have code like
6308 // int X = A < B;
6309 // if (X) ...
6310 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006311 // with a constant or another cast from the same type.
6312 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006313 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006314 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006315 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006316
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006317 // See if it's the same type of instruction on the left and right.
6318 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6319 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006320 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006321 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006322 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006323 default: break;
6324 case Instruction::Add:
6325 case Instruction::Sub:
6326 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006327 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006328 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006329 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006330 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6331 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6332 if (CI->getValue().isSignBit()) {
6333 ICmpInst::Predicate Pred = I.isSignedPredicate()
6334 ? I.getUnsignedPredicate()
6335 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006336 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006337 Op1I->getOperand(0));
6338 }
6339
6340 if (CI->getValue().isMaxSignedValue()) {
6341 ICmpInst::Predicate Pred = I.isSignedPredicate()
6342 ? I.getUnsignedPredicate()
6343 : I.getSignedPredicate();
6344 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006345 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006346 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006347 }
6348 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006349 break;
6350 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006351 if (!I.isEquality())
6352 break;
6353
Nick Lewycky5d52c452008-08-21 05:56:10 +00006354 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6355 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6356 // Mask = -1 >> count-trailing-zeros(Cst).
6357 if (!CI->isZero() && !CI->isOne()) {
6358 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006359 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006360 APInt::getLowBitsSet(AP.getBitWidth(),
6361 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006362 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006363 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6364 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006365 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006366 }
6367 }
6368 break;
6369 }
6370 }
6371 }
6372 }
6373
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006374 // ~x < ~y --> y < x
6375 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006376 if (match(Op0, m_Not(m_Value(A))) &&
6377 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006378 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006379 }
6380
Chris Lattner65b72ba2006-09-18 04:22:48 +00006381 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006382 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006383
6384 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006385 if (match(Op0, m_Neg(m_Value(A))) &&
6386 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006387 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006388
Dan Gohman4ae51262009-08-12 16:23:25 +00006389 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006390 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6391 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006392 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006393 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006394 }
6395
Dan Gohman4ae51262009-08-12 16:23:25 +00006396 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006397 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006398 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006399 if (match(B, m_ConstantInt(C1)) &&
6400 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006401 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006402 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006403 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6404 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006405 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006406
6407 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006408 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6409 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6410 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6411 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006412 }
6413 }
6414
Dan Gohman4ae51262009-08-12 16:23:25 +00006415 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006416 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006417 // A == (A^B) -> B == 0
6418 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006419 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006420 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006421 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006422
6423 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006424 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006425 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006426 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006427
6428 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006429 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006430 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006431 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006432
Chris Lattner9c2328e2006-11-14 06:06:06 +00006433 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6434 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006435 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6436 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006437 Value *X = 0, *Y = 0, *Z = 0;
6438
6439 if (A == C) {
6440 X = B; Y = D; Z = A;
6441 } else if (A == D) {
6442 X = B; Y = C; Z = A;
6443 } else if (B == C) {
6444 X = A; Y = D; Z = B;
6445 } else if (B == D) {
6446 X = A; Y = C; Z = B;
6447 }
6448
6449 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006450 Op1 = Builder->CreateXor(X, Y, "tmp");
6451 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006452 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006453 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006454 return &I;
6455 }
6456 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006457 }
Chris Lattner7e708292002-06-25 16:13:24 +00006458 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006459}
6460
Chris Lattner562ef782007-06-20 23:46:26 +00006461
6462/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6463/// and CmpRHS are both known to be integer constants.
6464Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6465 ConstantInt *DivRHS) {
6466 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6467 const APInt &CmpRHSV = CmpRHS->getValue();
6468
6469 // FIXME: If the operand types don't match the type of the divide
6470 // then don't attempt this transform. The code below doesn't have the
6471 // logic to deal with a signed divide and an unsigned compare (and
6472 // vice versa). This is because (x /s C1) <s C2 produces different
6473 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6474 // (x /u C1) <u C2. Simply casting the operands and result won't
6475 // work. :( The if statement below tests that condition and bails
6476 // if it finds it.
6477 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6478 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6479 return 0;
6480 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006481 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006482 if (DivIsSigned && DivRHS->isAllOnesValue())
6483 return 0; // The overflow computation also screws up here
6484 if (DivRHS->isOne())
6485 return 0; // Not worth bothering, and eliminates some funny cases
6486 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006487
6488 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6489 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6490 // C2 (CI). By solving for X we can turn this into a range check
6491 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006492 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006493
6494 // Determine if the product overflows by seeing if the product is
6495 // not equal to the divide. Make sure we do the same kind of divide
6496 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006497 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6498 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006499
6500 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006501 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006502
Chris Lattner1dbfd482007-06-21 18:11:19 +00006503 // Figure out the interval that is being checked. For example, a comparison
6504 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6505 // Compute this interval based on the constants involved and the signedness of
6506 // the compare/divide. This computes a half-open interval, keeping track of
6507 // whether either value in the interval overflows. After analysis each
6508 // overflow variable is set to 0 if it's corresponding bound variable is valid
6509 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6510 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006511 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006512
Chris Lattner562ef782007-06-20 23:46:26 +00006513 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006514 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006515 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006516 HiOverflow = LoOverflow = ProdOV;
6517 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006518 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006519 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006520 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006521 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006522 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006523 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006524 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006525 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6526 HiOverflow = LoOverflow = ProdOV;
6527 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006528 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006529 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006530 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006531 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006532 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6533 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006534 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006535 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006536 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006537 true) ? -1 : 0;
6538 }
Chris Lattner562ef782007-06-20 23:46:26 +00006539 }
Dan Gohman76491272008-02-13 22:09:18 +00006540 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006541 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006542 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006543 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006544 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006545 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6546 HiOverflow = 1; // [INTMIN+1, overflow)
6547 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6548 }
Dan Gohman76491272008-02-13 22:09:18 +00006549 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006550 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006551 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006552 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006553 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006554 LoOverflow = AddWithOverflow(LoBound, HiBound,
6555 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006556 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006557 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6558 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006559 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006560 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006561 }
6562
Chris Lattner1dbfd482007-06-21 18:11:19 +00006563 // Dividing by a negative swaps the condition. LT <-> GT
6564 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006565 }
6566
6567 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006568 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006569 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006570 case ICmpInst::ICMP_EQ:
6571 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006572 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006573 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006574 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006575 ICmpInst::ICMP_UGE, X, LoBound);
6576 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006577 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006578 ICmpInst::ICMP_ULT, X, HiBound);
6579 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006581 case ICmpInst::ICMP_NE:
6582 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006583 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006584 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006585 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006586 ICmpInst::ICMP_ULT, X, LoBound);
6587 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006588 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006589 ICmpInst::ICMP_UGE, X, HiBound);
6590 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006592 case ICmpInst::ICMP_ULT:
6593 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006595 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006597 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006598 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006599 case ICmpInst::ICMP_UGT:
6600 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006601 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006602 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006604 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006606 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006607 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006608 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006609 }
6610}
6611
6612
Chris Lattner01deb9d2007-04-03 17:43:25 +00006613/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6614///
6615Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6616 Instruction *LHSI,
6617 ConstantInt *RHS) {
6618 const APInt &RHSV = RHS->getValue();
6619
6620 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006621 case Instruction::Trunc:
6622 if (ICI.isEquality() && LHSI->hasOneUse()) {
6623 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6624 // of the high bits truncated out of x are known.
6625 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6626 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6627 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6628 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6629 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6630
6631 // If all the high bits are known, we can do this xform.
6632 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6633 // Pull in the high bits from known-ones set.
6634 APInt NewRHS(RHS->getValue());
6635 NewRHS.zext(SrcBits);
6636 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006637 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006638 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006639 }
6640 }
6641 break;
6642
Duncan Sands0091bf22007-04-04 06:42:45 +00006643 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006644 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6645 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6646 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006647 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6648 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006649 Value *CompareVal = LHSI->getOperand(0);
6650
6651 // If the sign bit of the XorCST is not set, there is no change to
6652 // the operation, just stop using the Xor.
6653 if (!XorCST->getValue().isNegative()) {
6654 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006655 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006656 return &ICI;
6657 }
6658
6659 // Was the old condition true if the operand is positive?
6660 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6661
6662 // If so, the new one isn't.
6663 isTrueIfPositive ^= true;
6664
6665 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006666 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006667 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006668 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006669 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006670 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006671 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006672
6673 if (LHSI->hasOneUse()) {
6674 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6675 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6676 const APInt &SignBit = XorCST->getValue();
6677 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6678 ? ICI.getUnsignedPredicate()
6679 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006680 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006681 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006682 }
6683
6684 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006685 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006686 const APInt &NotSignBit = XorCST->getValue();
6687 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6688 ? ICI.getUnsignedPredicate()
6689 : ICI.getSignedPredicate();
6690 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006691 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006692 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006693 }
6694 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006695 }
6696 break;
6697 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6698 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6699 LHSI->getOperand(0)->hasOneUse()) {
6700 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6701
6702 // If the LHS is an AND of a truncating cast, we can widen the
6703 // and/compare to be the input width without changing the value
6704 // produced, eliminating a cast.
6705 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6706 // We can do this transformation if either the AND constant does not
6707 // have its sign bit set or if it is an equality comparison.
6708 // Extending a relational comparison when we're checking the sign
6709 // bit would not work.
6710 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006711 (ICI.isEquality() ||
6712 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006713 uint32_t BitWidth =
6714 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6715 APInt NewCST = AndCST->getValue();
6716 NewCST.zext(BitWidth);
6717 APInt NewCI = RHSV;
6718 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006719 Value *NewAnd =
6720 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006721 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006722 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006723 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006724 }
6725 }
6726
6727 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6728 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6729 // happens a LOT in code produced by the C front-end, for bitfield
6730 // access.
6731 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6732 if (Shift && !Shift->isShift())
6733 Shift = 0;
6734
6735 ConstantInt *ShAmt;
6736 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6737 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6738 const Type *AndTy = AndCST->getType(); // Type of the and.
6739
6740 // We can fold this as long as we can't shift unknown bits
6741 // into the mask. This can only happen with signed shift
6742 // rights, as they sign-extend.
6743 if (ShAmt) {
6744 bool CanFold = Shift->isLogicalShift();
6745 if (!CanFold) {
6746 // To test for the bad case of the signed shr, see if any
6747 // of the bits shifted in could be tested after the mask.
6748 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6749 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6750
6751 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6752 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6753 AndCST->getValue()) == 0)
6754 CanFold = true;
6755 }
6756
6757 if (CanFold) {
6758 Constant *NewCst;
6759 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006760 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006761 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006762 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006763
6764 // Check to see if we are shifting out any of the bits being
6765 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006766 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006767 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006768 // If we shifted bits out, the fold is not going to work out.
6769 // As a special case, check to see if this means that the
6770 // result is always true or false now.
6771 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006772 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006773 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006774 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775 } else {
6776 ICI.setOperand(1, NewCst);
6777 Constant *NewAndCST;
6778 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006779 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006780 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006781 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 LHSI->setOperand(1, NewAndCST);
6783 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006784 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006785 return &ICI;
6786 }
6787 }
6788 }
6789
6790 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6791 // preferable because it allows the C<<Y expression to be hoisted out
6792 // of a loop if Y is invariant and X is not.
6793 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006794 ICI.isEquality() && !Shift->isArithmeticShift() &&
6795 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 // Compute C << Y.
6797 Value *NS;
6798 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006799 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006800 } else {
6801 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006802 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006803 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006804
6805 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006806 Value *NewAnd =
6807 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006808
6809 ICI.setOperand(0, NewAnd);
6810 return &ICI;
6811 }
6812 }
6813 break;
6814
Chris Lattnera0141b92007-07-15 20:42:37 +00006815 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6816 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6817 if (!ShAmt) break;
6818
6819 uint32_t TypeBits = RHSV.getBitWidth();
6820
6821 // Check that the shift amount is in range. If not, don't perform
6822 // undefined shifts. When the shift is visited it will be
6823 // simplified.
6824 if (ShAmt->uge(TypeBits))
6825 break;
6826
6827 if (ICI.isEquality()) {
6828 // If we are comparing against bits always shifted out, the
6829 // comparison cannot succeed.
6830 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006831 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006832 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006833 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6834 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006835 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006836 return ReplaceInstUsesWith(ICI, Cst);
6837 }
6838
6839 if (LHSI->hasOneUse()) {
6840 // Otherwise strength reduce the shift into an and.
6841 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6842 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006843 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006844 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006845
Chris Lattner74381062009-08-30 07:44:24 +00006846 Value *And =
6847 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006848 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006849 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006850 }
6851 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006852
6853 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6854 bool TrueIfSigned = false;
6855 if (LHSI->hasOneUse() &&
6856 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6857 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006858 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006859 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006860 Value *And =
6861 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006862 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006863 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006864 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006866 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006867
6868 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006869 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006870 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006871 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006872 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006873
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006874 // Check that the shift amount is in range. If not, don't perform
6875 // undefined shifts. When the shift is visited it will be
6876 // simplified.
6877 uint32_t TypeBits = RHSV.getBitWidth();
6878 if (ShAmt->uge(TypeBits))
6879 break;
6880
6881 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006882
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006883 // If we are comparing against bits always shifted out, the
6884 // comparison cannot succeed.
6885 APInt Comp = RHSV << ShAmtVal;
6886 if (LHSI->getOpcode() == Instruction::LShr)
6887 Comp = Comp.lshr(ShAmtVal);
6888 else
6889 Comp = Comp.ashr(ShAmtVal);
6890
6891 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6892 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006893 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006894 return ReplaceInstUsesWith(ICI, Cst);
6895 }
6896
6897 // Otherwise, check to see if the bits shifted out are known to be zero.
6898 // If so, we can compare against the unshifted value:
6899 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006900 if (LHSI->hasOneUse() &&
6901 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006902 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006903 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006904 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006905 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006906
Evan Chengf30752c2008-04-23 00:38:06 +00006907 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006908 // Otherwise strength reduce the shift into an and.
6909 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006910 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006911
Chris Lattner74381062009-08-30 07:44:24 +00006912 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6913 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006914 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006915 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006916 }
6917 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006918 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006919
6920 case Instruction::SDiv:
6921 case Instruction::UDiv:
6922 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6923 // Fold this div into the comparison, producing a range check.
6924 // Determine, based on the divide type, what the range is being
6925 // checked. If there is an overflow on the low or high side, remember
6926 // it, otherwise compute the range [low, hi) bounding the new value.
6927 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006928 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6929 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6930 DivRHS))
6931 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006932 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006933
6934 case Instruction::Add:
6935 // Fold: icmp pred (add, X, C1), C2
6936
6937 if (!ICI.isEquality()) {
6938 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6939 if (!LHSC) break;
6940 const APInt &LHSV = LHSC->getValue();
6941
6942 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6943 .subtract(LHSV);
6944
6945 if (ICI.isSignedPredicate()) {
6946 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006947 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006948 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006949 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006950 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006951 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006952 }
6953 } else {
6954 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006955 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006956 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006957 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006958 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006959 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006960 }
6961 }
6962 }
6963 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006964 }
6965
6966 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6967 if (ICI.isEquality()) {
6968 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6969
6970 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6971 // the second operand is a constant, simplify a bit.
6972 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6973 switch (BO->getOpcode()) {
6974 case Instruction::SRem:
6975 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6976 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6977 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6978 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006979 Value *NewRem =
6980 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6981 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006982 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006983 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006984 }
6985 }
6986 break;
6987 case Instruction::Add:
6988 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6989 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6990 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006991 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006992 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006993 } else if (RHSV == 0) {
6994 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6995 // efficiently invertible, or if the add has just this one use.
6996 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6997
Dan Gohman186a6362009-08-12 16:04:34 +00006998 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006999 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007000 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007001 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007002 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007003 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007004 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007005 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007006 }
7007 }
7008 break;
7009 case Instruction::Xor:
7010 // For the xor case, we can xor two constants together, eliminating
7011 // the explicit xor.
7012 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007013 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007014 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007015
7016 // FALLTHROUGH
7017 case Instruction::Sub:
7018 // Replace (([sub|xor] A, B) != 0) with (A != B)
7019 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007020 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007021 BO->getOperand(1));
7022 break;
7023
7024 case Instruction::Or:
7025 // If bits are being or'd in that are not present in the constant we
7026 // are comparing against, then the comparison could never succeed!
7027 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007028 Constant *NotCI = ConstantExpr::getNot(RHS);
7029 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007030 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007031 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007032 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007033 }
7034 break;
7035
7036 case Instruction::And:
7037 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7038 // If bits are being compared against that are and'd out, then the
7039 // comparison can never succeed!
7040 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007041 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007042 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007043 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007044
7045 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7046 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007047 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007048 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007049 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007050
7051 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007052 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007053 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007054 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007055 ICmpInst::Predicate pred = isICMP_NE ?
7056 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007057 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007058 }
7059
7060 // ((X & ~7) == 0) --> X < 8
7061 if (RHSV == 0 && isHighOnes(BOC)) {
7062 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007063 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007064 ICmpInst::Predicate pred = isICMP_NE ?
7065 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007066 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 }
7068 }
7069 default: break;
7070 }
7071 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7072 // Handle icmp {eq|ne} <intrinsic>, intcst.
7073 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007074 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007075 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007076 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 return &ICI;
7078 }
7079 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007080 }
7081 return 0;
7082}
7083
7084/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7085/// We only handle extending casts so far.
7086///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007087Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7088 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007089 Value *LHSCIOp = LHSCI->getOperand(0);
7090 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007091 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007092 Value *RHSCIOp;
7093
Chris Lattner8c756c12007-05-05 22:41:33 +00007094 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7095 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007096 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7097 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007098 cast<IntegerType>(DestTy)->getBitWidth()) {
7099 Value *RHSOp = 0;
7100 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007101 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007102 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7103 RHSOp = RHSC->getOperand(0);
7104 // If the pointer types don't match, insert a bitcast.
7105 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007106 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007107 }
7108
7109 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007110 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007111 }
7112
7113 // The code below only handles extension cast instructions, so far.
7114 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007115 if (LHSCI->getOpcode() != Instruction::ZExt &&
7116 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007117 return 0;
7118
Reid Spencere4d87aa2006-12-23 06:05:41 +00007119 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7120 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007121
Reid Spencere4d87aa2006-12-23 06:05:41 +00007122 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007123 // Not an extension from the same type?
7124 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007125 if (RHSCIOp->getType() != LHSCIOp->getType())
7126 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007127
Nick Lewycky4189a532008-01-28 03:48:02 +00007128 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007129 // and the other is a zext), then we can't handle this.
7130 if (CI->getOpcode() != LHSCI->getOpcode())
7131 return 0;
7132
Nick Lewycky4189a532008-01-28 03:48:02 +00007133 // Deal with equality cases early.
7134 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007135 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007136
7137 // A signed comparison of sign extended values simplifies into a
7138 // signed comparison.
7139 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007140 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007141
7142 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007143 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007144 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007145
Reid Spencere4d87aa2006-12-23 06:05:41 +00007146 // If we aren't dealing with a constant on the RHS, exit early
7147 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7148 if (!CI)
7149 return 0;
7150
7151 // Compute the constant that would happen if we truncated to SrcTy then
7152 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007153 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7154 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007155 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007156
7157 // If the re-extended constant didn't change...
7158 if (Res2 == CI) {
7159 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7160 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007161 // %A = sext i16 %X to i32
7162 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007163 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007164 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007165 // because %A may have negative value.
7166 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007167 // However, we allow this when the compare is EQ/NE, because they are
7168 // signless.
7169 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007170 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007171 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007172 }
7173
7174 // The re-extended constant changed so the constant cannot be represented
7175 // in the shorter type. Consequently, we cannot emit a simple comparison.
7176
7177 // First, handle some easy cases. We know the result cannot be equal at this
7178 // point so handle the ICI.isEquality() cases
7179 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007180 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007182 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007183
7184 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7185 // should have been folded away previously and not enter in here.
7186 Value *Result;
7187 if (isSignedCmp) {
7188 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007189 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007190 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007192 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007193 } else {
7194 // We're performing an unsigned comparison.
7195 if (isSignedExt) {
7196 // We're performing an unsigned comp with a sign extended value.
7197 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007198 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007199 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200 } else {
7201 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007202 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007203 }
7204 }
7205
7206 // Finally, return the value computed.
7207 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007208 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007209 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007210
7211 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7212 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7213 "ICmp should be folded!");
7214 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007215 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007216 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007217}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007218
Reid Spencer832254e2007-02-02 02:16:23 +00007219Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7220 return commonShiftTransforms(I);
7221}
7222
7223Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7224 return commonShiftTransforms(I);
7225}
7226
7227Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007228 if (Instruction *R = commonShiftTransforms(I))
7229 return R;
7230
7231 Value *Op0 = I.getOperand(0);
7232
7233 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7234 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7235 if (CSI->isAllOnesValue())
7236 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007237
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007238 // See if we can turn a signed shr into an unsigned shr.
7239 if (MaskedValueIsZero(Op0,
7240 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7241 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7242
7243 // Arithmetic shifting an all-sign-bit value is a no-op.
7244 unsigned NumSignBits = ComputeNumSignBits(Op0);
7245 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7246 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007247
Chris Lattner348f6652007-12-06 01:59:46 +00007248 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007249}
7250
7251Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7252 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007254
7255 // shl X, 0 == X and shr X, 0 == X
7256 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007257 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7258 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007259 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007260
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261 if (isa<UndefValue>(Op0)) {
7262 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007263 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007264 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007265 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007266 }
7267 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7269 return ReplaceInstUsesWith(I, Op0);
7270 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007271 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007272 }
7273
Dan Gohman9004c8a2009-05-21 02:28:33 +00007274 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007275 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007276 return &I;
7277
Chris Lattner2eefe512004-04-09 19:05:30 +00007278 // Try to fold constant and into select arguments.
7279 if (isa<Constant>(Op0))
7280 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007281 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007282 return R;
7283
Reid Spencerb83eb642006-10-20 07:07:24 +00007284 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007285 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7286 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007287 return 0;
7288}
7289
Reid Spencerb83eb642006-10-20 07:07:24 +00007290Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007291 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007292 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007293
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007294 // See if we can simplify any instructions used by the instruction whose sole
7295 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007296 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007297
Dan Gohmana119de82009-06-14 23:30:43 +00007298 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7299 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007300 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007301 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007302 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007303 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007304 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007305 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007306 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007307 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007308 }
7309
7310 // ((X*C1) << C2) == (X * (C1 << C2))
7311 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7312 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7313 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007314 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007315 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007316
7317 // Try to fold constant and into select arguments.
7318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7320 return R;
7321 if (isa<PHINode>(Op0))
7322 if (Instruction *NV = FoldOpIntoPhi(I))
7323 return NV;
7324
Chris Lattner8999dd32007-12-22 09:07:47 +00007325 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7326 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7327 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7328 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7329 // place. Don't try to do this transformation in this case. Also, we
7330 // require that the input operand is a shift-by-constant so that we have
7331 // confidence that the shifts will get folded together. We could do this
7332 // xform in more cases, but it is unlikely to be profitable.
7333 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7334 isa<ConstantInt>(TrOp->getOperand(1))) {
7335 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007336 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007337 // (shift2 (shift1 & 0x00FF), c2)
7338 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007339
7340 // For logical shifts, the truncation has the effect of making the high
7341 // part of the register be zeros. Emulate this by inserting an AND to
7342 // clear the top bits as needed. This 'and' will usually be zapped by
7343 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007344 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7345 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007346 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7347
7348 // The mask we constructed says what the trunc would do if occurring
7349 // between the shifts. We want to know the effect *after* the second
7350 // shift. We know that it is a logical shift by a constant, so adjust the
7351 // mask as appropriate.
7352 if (I.getOpcode() == Instruction::Shl)
7353 MaskV <<= Op1->getZExtValue();
7354 else {
7355 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7356 MaskV = MaskV.lshr(Op1->getZExtValue());
7357 }
7358
Chris Lattner74381062009-08-30 07:44:24 +00007359 // shift1 & 0x00FF
7360 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7361 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007362
7363 // Return the value truncated to the interesting size.
7364 return new TruncInst(And, I.getType());
7365 }
7366 }
7367
Chris Lattner4d5542c2006-01-06 07:12:35 +00007368 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007369 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7370 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7371 Value *V1, *V2;
7372 ConstantInt *CC;
7373 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007374 default: break;
7375 case Instruction::Add:
7376 case Instruction::And:
7377 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007378 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007379 // These operators commute.
7380 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007381 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007382 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007383 m_Specific(Op1)))) {
7384 Value *YS = // (Y << C)
7385 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7386 // (X + (Y << C))
7387 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7388 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007389 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007390 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007391 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007392 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007393
Chris Lattner150f12a2005-09-18 06:30:59 +00007394 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007395 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007396 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007397 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007398 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007399 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007400 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007401 Value *YS = // (Y << C)
7402 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7403 Op0BO->getName());
7404 // X & (CC << C)
7405 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7406 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007407 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007408 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007409 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410
Reid Spencera07cb7d2007-02-02 14:41:37 +00007411 // FALL THROUGH.
7412 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007413 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007414 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007415 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007416 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007417 Value *YS = // (Y << C)
7418 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7419 // (X + (Y << C))
7420 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7421 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007422 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007423 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007424 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007425 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007426
Chris Lattner13d4ab42006-05-31 21:14:00 +00007427 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007428 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7429 match(Op0BO->getOperand(0),
7430 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007431 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007432 cast<BinaryOperator>(Op0BO->getOperand(0))
7433 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007434 Value *YS = // (Y << C)
7435 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7436 // X & (CC << C)
7437 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7438 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007439
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007440 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007441 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007442
Chris Lattner11021cb2005-09-18 05:12:10 +00007443 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007444 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007445 }
7446
7447
7448 // If the operand is an bitwise operator with a constant RHS, and the
7449 // shift is the only use, we can pull it out of the shift.
7450 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7451 bool isValid = true; // Valid only for And, Or, Xor
7452 bool highBitSet = false; // Transform if high bit of constant set?
7453
7454 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007455 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007456 case Instruction::Add:
7457 isValid = isLeftShift;
7458 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007459 case Instruction::Or:
7460 case Instruction::Xor:
7461 highBitSet = false;
7462 break;
7463 case Instruction::And:
7464 highBitSet = true;
7465 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007466 }
7467
7468 // If this is a signed shift right, and the high bit is modified
7469 // by the logical operation, do not perform the transformation.
7470 // The highBitSet boolean indicates the value of the high bit of
7471 // the constant which would cause it to be modified for this
7472 // operation.
7473 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007474 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007475 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007476
7477 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007478 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007479
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007480 Value *NewShift =
7481 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007482 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007483
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007484 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007485 NewRHS);
7486 }
7487 }
7488 }
7489 }
7490
Chris Lattnerad0124c2006-01-06 07:52:12 +00007491 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007492 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7493 if (ShiftOp && !ShiftOp->isShift())
7494 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007495
Reid Spencerb83eb642006-10-20 07:07:24 +00007496 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007497 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007498 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7499 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007500 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7501 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7502 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007503
Zhou Sheng4351c642007-04-02 08:20:41 +00007504 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007505
7506 const IntegerType *Ty = cast<IntegerType>(I.getType());
7507
7508 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007509 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007510 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7511 // saturates.
7512 if (AmtSum >= TypeBits) {
7513 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007514 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007515 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7516 }
7517
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007518 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007519 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007520 }
7521
7522 if (ShiftOp->getOpcode() == Instruction::LShr &&
7523 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007524 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007525 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007526
Chris Lattnerb87056f2007-02-05 00:57:54 +00007527 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007528 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007529 }
7530
7531 if (ShiftOp->getOpcode() == Instruction::AShr &&
7532 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007533 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007534 if (AmtSum >= TypeBits)
7535 AmtSum = TypeBits-1;
7536
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007537 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007538
Zhou Shenge9e03f62007-03-28 15:02:20 +00007539 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007540 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007541 }
7542
Chris Lattnerb87056f2007-02-05 00:57:54 +00007543 // Okay, if we get here, one shift must be left, and the other shift must be
7544 // right. See if the amounts are equal.
7545 if (ShiftAmt1 == ShiftAmt2) {
7546 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7547 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007548 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007549 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007550 }
7551 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7552 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007553 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007554 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007555 }
7556 // We can simplify ((X << C) >>s C) into a trunc + sext.
7557 // NOTE: we could do this for any C, but that would make 'unusual' integer
7558 // types. For now, just stick to ones well-supported by the code
7559 // generators.
7560 const Type *SExtType = 0;
7561 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007562 case 1 :
7563 case 8 :
7564 case 16 :
7565 case 32 :
7566 case 64 :
7567 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007568 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007569 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007570 default: break;
7571 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007572 if (SExtType)
7573 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007574 // Otherwise, we can't handle it yet.
7575 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007576 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007577
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007578 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007579 if (I.getOpcode() == Instruction::Shl) {
7580 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7581 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007582 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007583
Reid Spencer55702aa2007-03-25 21:11:44 +00007584 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007585 return BinaryOperator::CreateAnd(Shift,
7586 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007587 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007588
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007589 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007590 if (I.getOpcode() == Instruction::LShr) {
7591 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007592 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007593
Reid Spencerd5e30f02007-03-26 17:18:58 +00007594 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007595 return BinaryOperator::CreateAnd(Shift,
7596 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007597 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007598
7599 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7600 } else {
7601 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007602 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007603
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007604 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007605 if (I.getOpcode() == Instruction::Shl) {
7606 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7607 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007608 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7609 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007610
Reid Spencer55702aa2007-03-25 21:11:44 +00007611 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007612 return BinaryOperator::CreateAnd(Shift,
7613 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007614 }
7615
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007616 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007617 if (I.getOpcode() == Instruction::LShr) {
7618 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007619 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007620
Reid Spencer68d27cf2007-03-26 23:45:51 +00007621 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007622 return BinaryOperator::CreateAnd(Shift,
7623 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007624 }
7625
7626 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007627 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007628 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007629 return 0;
7630}
7631
Chris Lattnera1be5662002-05-02 17:06:02 +00007632
Chris Lattnercfd65102005-10-29 04:36:15 +00007633/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7634/// expression. If so, decompose it, returning some value X, such that Val is
7635/// X*Scale+Offset.
7636///
7637static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007638 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007639 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7640 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007641 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007642 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007643 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007644 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007645 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7646 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7647 if (I->getOpcode() == Instruction::Shl) {
7648 // This is a value scaled by '1 << the shift amt'.
7649 Scale = 1U << RHS->getZExtValue();
7650 Offset = 0;
7651 return I->getOperand(0);
7652 } else if (I->getOpcode() == Instruction::Mul) {
7653 // This value is scaled by 'RHS'.
7654 Scale = RHS->getZExtValue();
7655 Offset = 0;
7656 return I->getOperand(0);
7657 } else if (I->getOpcode() == Instruction::Add) {
7658 // We have X+C. Check to see if we really have (X*C2)+C1,
7659 // where C1 is divisible by C2.
7660 unsigned SubScale;
7661 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007662 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7663 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007664 Offset += RHS->getZExtValue();
7665 Scale = SubScale;
7666 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007667 }
7668 }
7669 }
7670
7671 // Otherwise, we can't look past this.
7672 Scale = 1;
7673 Offset = 0;
7674 return Val;
7675}
7676
7677
Chris Lattnerb3f83972005-10-24 06:03:58 +00007678/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7679/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007680Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007681 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007682 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007683
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007684 BuilderTy AllocaBuilder(*Builder);
7685 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7686
Chris Lattnerb53c2382005-10-24 06:22:12 +00007687 // Remove any uses of AI that are dead.
7688 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007689
Chris Lattnerb53c2382005-10-24 06:22:12 +00007690 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7691 Instruction *User = cast<Instruction>(*UI++);
7692 if (isInstructionTriviallyDead(User)) {
7693 while (UI != E && *UI == User)
7694 ++UI; // If this instruction uses AI more than once, don't break UI.
7695
Chris Lattnerb53c2382005-10-24 06:22:12 +00007696 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007697 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007698 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007699 }
7700 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007701
7702 // This requires TargetData to get the alloca alignment and size information.
7703 if (!TD) return 0;
7704
Chris Lattnerb3f83972005-10-24 06:03:58 +00007705 // Get the type really allocated and the type casted to.
7706 const Type *AllocElTy = AI.getAllocatedType();
7707 const Type *CastElTy = PTy->getElementType();
7708 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007709
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007710 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7711 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007712 if (CastElTyAlign < AllocElTyAlign) return 0;
7713
Chris Lattner39387a52005-10-24 06:35:18 +00007714 // If the allocation has multiple uses, only promote it if we are strictly
7715 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007716 // same, we open the door to infinite loops of various kinds. (A reference
7717 // from a dbg.declare doesn't count as a use for this purpose.)
7718 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7719 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007720
Duncan Sands777d2302009-05-09 07:06:46 +00007721 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7722 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007723 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007724
Chris Lattner455fcc82005-10-29 03:19:53 +00007725 // See if we can satisfy the modulus by pulling a scale out of the array
7726 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007727 unsigned ArraySizeScale;
7728 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007729 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007730 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7731 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007732
Chris Lattner455fcc82005-10-29 03:19:53 +00007733 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7734 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007735 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7736 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007737
Chris Lattner455fcc82005-10-29 03:19:53 +00007738 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7739 Value *Amt = 0;
7740 if (Scale == 1) {
7741 Amt = NumElements;
7742 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007743 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007744 // Insert before the alloca, not before the cast.
7745 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007746 }
7747
Jeff Cohen86796be2007-04-04 16:58:57 +00007748 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007749 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007750 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007751 }
7752
Chris Lattnerb3f83972005-10-24 06:03:58 +00007753 AllocationInst *New;
7754 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007755 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007756 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007757 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7758 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007759 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007760
Dale Johannesena0a66372009-03-05 00:39:02 +00007761 // If the allocation has one real use plus a dbg.declare, just remove the
7762 // declare.
7763 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7764 EraseInstFromFunction(*DI);
7765 }
7766 // If the allocation has multiple real uses, insert a cast and change all
7767 // things that used it to use the new cast. This will also hack on CI, but it
7768 // will die soon.
7769 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007770 // New is the allocation instruction, pointer typed. AI is the original
7771 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007772 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007773 AI.replaceAllUsesWith(NewCast);
7774 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007775 return ReplaceInstUsesWith(CI, New);
7776}
7777
Chris Lattner70074e02006-05-13 02:06:03 +00007778/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007779/// and return it as type Ty without inserting any new casts and without
7780/// changing the computed value. This is used by code that tries to decide
7781/// whether promoting or shrinking integer operations to wider or smaller types
7782/// will allow us to eliminate a truncate or extend.
7783///
7784/// This is a truncation operation if Ty is smaller than V->getType(), or an
7785/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007786///
7787/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7788/// should return true if trunc(V) can be computed by computing V in the smaller
7789/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7790/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7791/// efficiently truncated.
7792///
7793/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7794/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7795/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007796bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007797 unsigned CastOpc,
7798 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007799 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007800 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007801 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007802
7803 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007804 if (!I) return false;
7805
Dan Gohman6de29f82009-06-15 22:12:54 +00007806 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007807
Chris Lattner951626b2007-08-02 06:11:14 +00007808 // If this is an extension or truncate, we can often eliminate it.
7809 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7810 // If this is a cast from the destination type, we can trivially eliminate
7811 // it, and this will remove a cast overall.
7812 if (I->getOperand(0)->getType() == Ty) {
7813 // If the first operand is itself a cast, and is eliminable, do not count
7814 // this as an eliminable cast. We would prefer to eliminate those two
7815 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007816 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007817 ++NumCastsRemoved;
7818 return true;
7819 }
7820 }
7821
7822 // We can't extend or shrink something that has multiple uses: doing so would
7823 // require duplicating the instruction in general, which isn't profitable.
7824 if (!I->hasOneUse()) return false;
7825
Evan Chengf35fd542009-01-15 17:01:23 +00007826 unsigned Opc = I->getOpcode();
7827 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007828 case Instruction::Add:
7829 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007830 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007831 case Instruction::And:
7832 case Instruction::Or:
7833 case Instruction::Xor:
7834 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007835 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007836 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007837 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007838 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007839
Eli Friedman070a9812009-07-13 22:46:01 +00007840 case Instruction::UDiv:
7841 case Instruction::URem: {
7842 // UDiv and URem can be truncated if all the truncated bits are zero.
7843 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7844 uint32_t BitWidth = Ty->getScalarSizeInBits();
7845 if (BitWidth < OrigBitWidth) {
7846 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7847 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7848 MaskedValueIsZero(I->getOperand(1), Mask)) {
7849 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7850 NumCastsRemoved) &&
7851 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7852 NumCastsRemoved);
7853 }
7854 }
7855 break;
7856 }
Chris Lattner46b96052006-11-29 07:18:39 +00007857 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007858 // If we are truncating the result of this SHL, and if it's a shift of a
7859 // constant amount, we can always perform a SHL in a smaller type.
7860 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007861 uint32_t BitWidth = Ty->getScalarSizeInBits();
7862 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007863 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007864 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007865 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007866 }
7867 break;
7868 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007869 // If this is a truncate of a logical shr, we can truncate it to a smaller
7870 // lshr iff we know that the bits we would otherwise be shifting in are
7871 // already zeros.
7872 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007873 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7874 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007875 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007876 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007877 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7878 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007879 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007880 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007881 }
7882 }
Chris Lattner46b96052006-11-29 07:18:39 +00007883 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007884 case Instruction::ZExt:
7885 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007886 case Instruction::Trunc:
7887 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007888 // can safely replace it. Note that replacing it does not reduce the number
7889 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007890 if (Opc == CastOpc)
7891 return true;
7892
7893 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007894 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007895 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007896 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007897 case Instruction::Select: {
7898 SelectInst *SI = cast<SelectInst>(I);
7899 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007900 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007901 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007902 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007903 }
Chris Lattner8114b712008-06-18 04:00:49 +00007904 case Instruction::PHI: {
7905 // We can change a phi if we can change all operands.
7906 PHINode *PN = cast<PHINode>(I);
7907 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7908 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007909 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007910 return false;
7911 return true;
7912 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007913 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007914 // TODO: Can handle more cases here.
7915 break;
7916 }
7917
7918 return false;
7919}
7920
7921/// EvaluateInDifferentType - Given an expression that
7922/// CanEvaluateInDifferentType returns true for, actually insert the code to
7923/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007924Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007925 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007926 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007927 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007928 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007929
7930 // Otherwise, it must be an instruction.
7931 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007932 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007933 unsigned Opc = I->getOpcode();
7934 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007935 case Instruction::Add:
7936 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007937 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007938 case Instruction::And:
7939 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007941 case Instruction::AShr:
7942 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007943 case Instruction::Shl:
7944 case Instruction::UDiv:
7945 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007946 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007947 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007948 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007949 break;
7950 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007951 case Instruction::Trunc:
7952 case Instruction::ZExt:
7953 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007954 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007955 // just return the source. There's no need to insert it because it is not
7956 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007957 if (I->getOperand(0)->getType() == Ty)
7958 return I->getOperand(0);
7959
Chris Lattner8114b712008-06-18 04:00:49 +00007960 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007961 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007962 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007963 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007964 case Instruction::Select: {
7965 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7966 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7967 Res = SelectInst::Create(I->getOperand(0), True, False);
7968 break;
7969 }
Chris Lattner8114b712008-06-18 04:00:49 +00007970 case Instruction::PHI: {
7971 PHINode *OPN = cast<PHINode>(I);
7972 PHINode *NPN = PHINode::Create(Ty);
7973 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7974 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7975 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7976 }
7977 Res = NPN;
7978 break;
7979 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007980 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007981 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00007982 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00007983 break;
7984 }
7985
Chris Lattner8114b712008-06-18 04:00:49 +00007986 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007987 return InsertNewInstBefore(Res, *I);
7988}
7989
Reid Spencer3da59db2006-11-27 01:05:10 +00007990/// @brief Implement the transforms common to all CastInst visitors.
7991Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007992 Value *Src = CI.getOperand(0);
7993
Dan Gohman23d9d272007-05-11 21:10:54 +00007994 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007995 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007996 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007997 if (Instruction::CastOps opc =
7998 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7999 // The first cast (CSrc) is eliminable so we need to fix up or replace
8000 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008001 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008002 }
8003 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008004
Reid Spencer3da59db2006-11-27 01:05:10 +00008005 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008006 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8007 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8008 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008009
8010 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008011 if (isa<PHINode>(Src))
8012 if (Instruction *NV = FoldOpIntoPhi(CI))
8013 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008014
Reid Spencer3da59db2006-11-27 01:05:10 +00008015 return 0;
8016}
8017
Chris Lattner46cd5a12009-01-09 05:44:56 +00008018/// FindElementAtOffset - Given a type and a constant offset, determine whether
8019/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008020/// the specified offset. If so, fill them into NewIndices and return the
8021/// resultant element type, otherwise return null.
8022static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8023 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008024 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008025 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008026 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008027 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008028
8029 // Start with the index over the outer type. Note that the type size
8030 // might be zero (even if the offset isn't zero) if the indexed type
8031 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008032 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008033 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008034 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008035 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008036 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008037
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008038 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008039 if (Offset < 0) {
8040 --FirstIdx;
8041 Offset += TySize;
8042 assert(Offset >= 0);
8043 }
8044 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8045 }
8046
Owen Andersoneed707b2009-07-24 23:12:02 +00008047 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008048
8049 // Index into the types. If we fail, set OrigBase to null.
8050 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008051 // Indexing into tail padding between struct/array elements.
8052 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008053 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008054
Chris Lattner46cd5a12009-01-09 05:44:56 +00008055 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8056 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008057 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8058 "Offset must stay within the indexed type");
8059
Chris Lattner46cd5a12009-01-09 05:44:56 +00008060 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008061 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008062
8063 Offset -= SL->getElementOffset(Elt);
8064 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008065 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008066 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008067 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008068 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008069 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008070 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008071 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008072 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008073 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008074 }
8075 }
8076
Chris Lattner3914f722009-01-24 01:00:13 +00008077 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008078}
8079
Chris Lattnerd3e28342007-04-27 17:44:50 +00008080/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8081Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8082 Value *Src = CI.getOperand(0);
8083
Chris Lattnerd3e28342007-04-27 17:44:50 +00008084 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008085 // If casting the result of a getelementptr instruction with no offset, turn
8086 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008087 if (GEP->hasAllZeroIndices()) {
8088 // Changing the cast operand is usually not a good idea but it is safe
8089 // here because the pointer operand is being replaced with another
8090 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008091 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008092 CI.setOperand(0, GEP->getOperand(0));
8093 return &CI;
8094 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008095
8096 // If the GEP has a single use, and the base pointer is a bitcast, and the
8097 // GEP computes a constant offset, see if we can convert these three
8098 // instructions into fewer. This typically happens with unions and other
8099 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008100 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008101 if (GEP->hasAllConstantIndices()) {
8102 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008103 ConstantInt *OffsetV =
8104 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008105 int64_t Offset = OffsetV->getSExtValue();
8106
8107 // Get the base pointer input of the bitcast, and the type it points to.
8108 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8109 const Type *GEPIdxTy =
8110 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008111 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008112 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008113 // If we were able to index down into an element, create the GEP
8114 // and bitcast the result. This eliminates one bitcast, potentially
8115 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008116 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8117 Builder->CreateInBoundsGEP(OrigBase,
8118 NewIndices.begin(), NewIndices.end()) :
8119 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008120 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008121
Chris Lattner46cd5a12009-01-09 05:44:56 +00008122 if (isa<BitCastInst>(CI))
8123 return new BitCastInst(NGEP, CI.getType());
8124 assert(isa<PtrToIntInst>(CI));
8125 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008126 }
8127 }
8128 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008129 }
8130
8131 return commonCastTransforms(CI);
8132}
8133
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008134/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8135/// type like i42. We don't want to introduce operations on random non-legal
8136/// integer types where they don't already exist in the code. In the future,
8137/// we should consider making this based off target-data, so that 32-bit targets
8138/// won't get i64 operations etc.
8139static bool isSafeIntegerType(const Type *Ty) {
8140 switch (Ty->getPrimitiveSizeInBits()) {
8141 case 8:
8142 case 16:
8143 case 32:
8144 case 64:
8145 return true;
8146 default:
8147 return false;
8148 }
8149}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008150
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008151/// commonIntCastTransforms - This function implements the common transforms
8152/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008153Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8154 if (Instruction *Result = commonCastTransforms(CI))
8155 return Result;
8156
8157 Value *Src = CI.getOperand(0);
8158 const Type *SrcTy = Src->getType();
8159 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008160 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8161 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008162
Reid Spencer3da59db2006-11-27 01:05:10 +00008163 // See if we can simplify any instructions used by the LHS whose sole
8164 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008165 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008166 return &CI;
8167
8168 // If the source isn't an instruction or has more than one use then we
8169 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008170 Instruction *SrcI = dyn_cast<Instruction>(Src);
8171 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008172 return 0;
8173
Chris Lattnerc739cd62007-03-03 05:27:34 +00008174 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008175 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008176 // Only do this if the dest type is a simple type, don't convert the
8177 // expression tree to something weird like i93 unless the source is also
8178 // strange.
8179 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008180 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8181 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008182 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008183 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008184 // eliminates the cast, so it is always a win. If this is a zero-extension,
8185 // we need to do an AND to maintain the clear top-part of the computation,
8186 // so we require that the input have eliminated at least one cast. If this
8187 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008188 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008189 bool DoXForm = false;
8190 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008191 switch (CI.getOpcode()) {
8192 default:
8193 // All the others use floating point so we shouldn't actually
8194 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008195 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008196 case Instruction::Trunc:
8197 DoXForm = true;
8198 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008199 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008200 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008201 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008202 // If it's unnecessary to issue an AND to clear the high bits, it's
8203 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008204 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008205 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8206 if (MaskedValueIsZero(TryRes, Mask))
8207 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008208
8209 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008210 if (TryI->use_empty())
8211 EraseInstFromFunction(*TryI);
8212 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008213 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008214 }
Evan Chengf35fd542009-01-15 17:01:23 +00008215 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008216 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008217 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008218 // If we do not have to emit the truncate + sext pair, then it's always
8219 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008220 //
8221 // It's not safe to eliminate the trunc + sext pair if one of the
8222 // eliminated cast is a truncate. e.g.
8223 // t2 = trunc i32 t1 to i16
8224 // t3 = sext i16 t2 to i32
8225 // !=
8226 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008227 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008228 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8229 if (NumSignBits > (DestBitSize - SrcBitSize))
8230 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008231
8232 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008233 if (TryI->use_empty())
8234 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008235 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008236 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008237 }
Evan Chengf35fd542009-01-15 17:01:23 +00008238 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008239
8240 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008241 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8242 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008243 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8244 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008245 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008246 // Just replace this cast with the result.
8247 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008248
Reid Spencer3da59db2006-11-27 01:05:10 +00008249 assert(Res->getType() == DestTy);
8250 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008251 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008252 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008253 // Just replace this cast with the result.
8254 return ReplaceInstUsesWith(CI, Res);
8255 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008256 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008257
8258 // If the high bits are already zero, just replace this cast with the
8259 // result.
8260 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8261 if (MaskedValueIsZero(Res, Mask))
8262 return ReplaceInstUsesWith(CI, Res);
8263
8264 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008265 Constant *C = ConstantInt::get(*Context,
8266 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008267 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008268 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008269 case Instruction::SExt: {
8270 // If the high bits are already filled with sign bit, just replace this
8271 // cast with the result.
8272 unsigned NumSignBits = ComputeNumSignBits(Res);
8273 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008274 return ReplaceInstUsesWith(CI, Res);
8275
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008277 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008278 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008279 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008280 }
8281 }
8282
8283 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8284 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8285
8286 switch (SrcI->getOpcode()) {
8287 case Instruction::Add:
8288 case Instruction::Mul:
8289 case Instruction::And:
8290 case Instruction::Or:
8291 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008292 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008293 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8294 // Don't insert two casts unless at least one can be eliminated.
8295 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008296 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008297 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8298 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008299 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008300 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008301 }
8302 }
8303
8304 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8305 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8306 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008307 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008308 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008309 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008310 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008311 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 }
8313 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008314
Eli Friedman65445c52009-07-13 21:45:57 +00008315 case Instruction::Shl: {
8316 // Canonicalize trunc inside shl, if we can.
8317 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8318 if (CI && DestBitSize < SrcBitSize &&
8319 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008320 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8321 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008322 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008323 }
8324 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008325 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008326 }
8327 return 0;
8328}
8329
Chris Lattner8a9f5712007-04-11 06:57:46 +00008330Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008331 if (Instruction *Result = commonIntCastTransforms(CI))
8332 return Result;
8333
8334 Value *Src = CI.getOperand(0);
8335 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008336 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8337 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008338
8339 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008340 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008341 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008342 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008343 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008344 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008345 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008346
Chris Lattner4f9797d2009-03-24 18:15:30 +00008347 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8348 ConstantInt *ShAmtV = 0;
8349 Value *ShiftOp = 0;
8350 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008351 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008352 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8353
8354 // Get a mask for the bits shifting in.
8355 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8356 if (MaskedValueIsZero(ShiftOp, Mask)) {
8357 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008358 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008359
8360 // Okay, we can shrink this. Truncate the input, then return a new
8361 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008362 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008363 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008364 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008365 }
8366 }
8367
8368 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008369}
8370
Evan Chengb98a10e2008-03-24 00:21:34 +00008371/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8372/// in order to eliminate the icmp.
8373Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8374 bool DoXform) {
8375 // If we are just checking for a icmp eq of a single bit and zext'ing it
8376 // to an integer, then shift the bit to the appropriate place and then
8377 // cast to integer to avoid the comparison.
8378 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8379 const APInt &Op1CV = Op1C->getValue();
8380
8381 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8382 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8383 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8384 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8385 if (!DoXform) return ICI;
8386
8387 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008388 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008389 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008390 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008391 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008392 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008393
8394 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008395 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008396 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008397 }
8398
8399 return ReplaceInstUsesWith(CI, In);
8400 }
8401
8402
8403
8404 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8405 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8406 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8407 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8408 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8409 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8410 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8411 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8412 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8413 // This only works for EQ and NE
8414 ICI->isEquality()) {
8415 // If Op1C some other power of two, convert:
8416 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8417 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8418 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8419 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8420
8421 APInt KnownZeroMask(~KnownZero);
8422 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8423 if (!DoXform) return ICI;
8424
8425 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8426 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8427 // (X&4) == 2 --> false
8428 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008429 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008430 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008431 return ReplaceInstUsesWith(CI, Res);
8432 }
8433
8434 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8435 Value *In = ICI->getOperand(0);
8436 if (ShiftAmt) {
8437 // Perform a logical shr by shiftamt.
8438 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008439 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8440 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008441 }
8442
8443 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008444 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008445 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008446 }
8447
8448 if (CI.getType() == In->getType())
8449 return ReplaceInstUsesWith(CI, In);
8450 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008451 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008452 }
8453 }
8454 }
8455
8456 return 0;
8457}
8458
Chris Lattner8a9f5712007-04-11 06:57:46 +00008459Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008460 // If one of the common conversion will work ..
8461 if (Instruction *Result = commonIntCastTransforms(CI))
8462 return Result;
8463
8464 Value *Src = CI.getOperand(0);
8465
Chris Lattnera84f47c2009-02-17 20:47:23 +00008466 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8467 // types and if the sizes are just right we can convert this into a logical
8468 // 'and' which will be much cheaper than the pair of casts.
8469 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8470 // Get the sizes of the types involved. We know that the intermediate type
8471 // will be smaller than A or C, but don't know the relation between A and C.
8472 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008473 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8474 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8475 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008476 // If we're actually extending zero bits, then if
8477 // SrcSize < DstSize: zext(a & mask)
8478 // SrcSize == DstSize: a & mask
8479 // SrcSize > DstSize: trunc(a) & mask
8480 if (SrcSize < DstSize) {
8481 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008482 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008483 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008484 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008485 }
8486
8487 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008488 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008489 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008490 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008491 }
8492 if (SrcSize > DstSize) {
8493 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008494 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008495 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008496 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008497 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008498 }
8499 }
8500
Evan Chengb98a10e2008-03-24 00:21:34 +00008501 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8502 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008503
Evan Chengb98a10e2008-03-24 00:21:34 +00008504 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8505 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8506 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8507 // of the (zext icmp) will be transformed.
8508 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8509 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8510 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8511 (transformZExtICmp(LHS, CI, false) ||
8512 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008513 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8514 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008515 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008516 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008517 }
8518
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008519 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008520 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8521 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8522 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8523 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008524 if (TI0->getType() == CI.getType())
8525 return
8526 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008527 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008528 }
8529
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008530 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8531 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8532 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8533 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8534 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8535 And->getOperand(1) == C)
8536 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8537 Value *TI0 = TI->getOperand(0);
8538 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008539 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008540 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008541 return BinaryOperator::CreateXor(NewAnd, ZC);
8542 }
8543 }
8544
Reid Spencer3da59db2006-11-27 01:05:10 +00008545 return 0;
8546}
8547
Chris Lattner8a9f5712007-04-11 06:57:46 +00008548Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008549 if (Instruction *I = commonIntCastTransforms(CI))
8550 return I;
8551
Chris Lattner8a9f5712007-04-11 06:57:46 +00008552 Value *Src = CI.getOperand(0);
8553
Dan Gohman1975d032008-10-30 20:40:10 +00008554 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008555 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008556 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008557 Constant::getAllOnesValue(CI.getType()),
8558 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008559
8560 // See if the value being truncated is already sign extended. If so, just
8561 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008562 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008563 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008564 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8565 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8566 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008567 unsigned NumSignBits = ComputeNumSignBits(Op);
8568
8569 if (OpBits == DestBits) {
8570 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8571 // bits, it is already ready.
8572 if (NumSignBits > DestBits-MidBits)
8573 return ReplaceInstUsesWith(CI, Op);
8574 } else if (OpBits < DestBits) {
8575 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8576 // bits, just sext from i32.
8577 if (NumSignBits > OpBits-MidBits)
8578 return new SExtInst(Op, CI.getType(), "tmp");
8579 } else {
8580 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8581 // bits, just truncate to i32.
8582 if (NumSignBits > OpBits-MidBits)
8583 return new TruncInst(Op, CI.getType(), "tmp");
8584 }
8585 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008586
8587 // If the input is a shl/ashr pair of a same constant, then this is a sign
8588 // extension from a smaller value. If we could trust arbitrary bitwidth
8589 // integers, we could turn this into a truncate to the smaller bit and then
8590 // use a sext for the whole extension. Since we don't, look deeper and check
8591 // for a truncate. If the source and dest are the same type, eliminate the
8592 // trunc and extend and just do shifts. For example, turn:
8593 // %a = trunc i32 %i to i8
8594 // %b = shl i8 %a, 6
8595 // %c = ashr i8 %b, 6
8596 // %d = sext i8 %c to i32
8597 // into:
8598 // %a = shl i32 %i, 30
8599 // %d = ashr i32 %a, 30
8600 Value *A = 0;
8601 ConstantInt *BA = 0, *CA = 0;
8602 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008603 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008604 BA == CA && isa<TruncInst>(A)) {
8605 Value *I = cast<TruncInst>(A)->getOperand(0);
8606 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008607 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8608 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008609 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008610 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008611 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008612 return BinaryOperator::CreateAShr(I, ShAmtV);
8613 }
8614 }
8615
Chris Lattnerba417832007-04-11 06:12:58 +00008616 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008617}
8618
Chris Lattnerb7530652008-01-27 05:29:54 +00008619/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8620/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008621static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008622 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008623 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008624 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008625 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8626 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008627 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008628 return 0;
8629}
8630
8631/// LookThroughFPExtensions - If this is an fp extension instruction, look
8632/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008633static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008634 if (Instruction *I = dyn_cast<Instruction>(V))
8635 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008636 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008637
8638 // If this value is a constant, return the constant in the smallest FP type
8639 // that can accurately represent it. This allows us to turn
8640 // (float)((double)X+2.0) into x+2.0f.
8641 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008642 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008643 return V; // No constant folding of this.
8644 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008645 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008646 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008647 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008648 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008649 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008650 return V;
8651 // Don't try to shrink to various long double types.
8652 }
8653
8654 return V;
8655}
8656
8657Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8658 if (Instruction *I = commonCastTransforms(CI))
8659 return I;
8660
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008661 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008662 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008663 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008664 // many builtins (sqrt, etc).
8665 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8666 if (OpI && OpI->hasOneUse()) {
8667 switch (OpI->getOpcode()) {
8668 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008669 case Instruction::FAdd:
8670 case Instruction::FSub:
8671 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008672 case Instruction::FDiv:
8673 case Instruction::FRem:
8674 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008675 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8676 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008677 if (LHSTrunc->getType() != SrcTy &&
8678 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008679 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008680 // If the source types were both smaller than the destination type of
8681 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008682 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8683 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008684 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8685 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008686 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008687 }
8688 }
8689 break;
8690 }
8691 }
8692 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008693}
8694
8695Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8696 return commonCastTransforms(CI);
8697}
8698
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008699Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008700 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8701 if (OpI == 0)
8702 return commonCastTransforms(FI);
8703
8704 // fptoui(uitofp(X)) --> X
8705 // fptoui(sitofp(X)) --> X
8706 // This is safe if the intermediate type has enough bits in its mantissa to
8707 // accurately represent all values of X. For example, do not do this with
8708 // i64->float->i64. This is also safe for sitofp case, because any negative
8709 // 'X' value would cause an undefined result for the fptoui.
8710 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8711 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008712 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008713 OpI->getType()->getFPMantissaWidth())
8714 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008715
8716 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008717}
8718
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008719Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008720 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8721 if (OpI == 0)
8722 return commonCastTransforms(FI);
8723
8724 // fptosi(sitofp(X)) --> X
8725 // fptosi(uitofp(X)) --> X
8726 // This is safe if the intermediate type has enough bits in its mantissa to
8727 // accurately represent all values of X. For example, do not do this with
8728 // i64->float->i64. This is also safe for sitofp case, because any negative
8729 // 'X' value would cause an undefined result for the fptoui.
8730 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8731 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008732 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008733 OpI->getType()->getFPMantissaWidth())
8734 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008735
8736 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008737}
8738
8739Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8740 return commonCastTransforms(CI);
8741}
8742
8743Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8744 return commonCastTransforms(CI);
8745}
8746
Chris Lattnera0e69692009-03-24 18:35:40 +00008747Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8748 // If the destination integer type is smaller than the intptr_t type for
8749 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8750 // trunc to be exposed to other transforms. Don't do this for extending
8751 // ptrtoint's, because we don't know if the target sign or zero extends its
8752 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008753 if (TD &&
8754 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008755 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8756 TD->getIntPtrType(CI.getContext()),
8757 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008758 return new TruncInst(P, CI.getType());
8759 }
8760
Chris Lattnerd3e28342007-04-27 17:44:50 +00008761 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008762}
8763
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008764Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008765 // If the source integer type is larger than the intptr_t type for
8766 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8767 // allows the trunc to be exposed to other transforms. Don't do this for
8768 // extending inttoptr's, because we don't know if the target sign or zero
8769 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008770 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008771 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008772 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8773 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008774 return new IntToPtrInst(P, CI.getType());
8775 }
8776
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008777 if (Instruction *I = commonCastTransforms(CI))
8778 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008779
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008780 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008781}
8782
Chris Lattnerd3e28342007-04-27 17:44:50 +00008783Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008784 // If the operands are integer typed then apply the integer transforms,
8785 // otherwise just apply the common ones.
8786 Value *Src = CI.getOperand(0);
8787 const Type *SrcTy = Src->getType();
8788 const Type *DestTy = CI.getType();
8789
Eli Friedman7e25d452009-07-13 20:53:00 +00008790 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008791 if (Instruction *I = commonPointerCastTransforms(CI))
8792 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008793 } else {
8794 if (Instruction *Result = commonCastTransforms(CI))
8795 return Result;
8796 }
8797
8798
8799 // Get rid of casts from one type to the same type. These are useless and can
8800 // be replaced by the operand.
8801 if (DestTy == Src->getType())
8802 return ReplaceInstUsesWith(CI, Src);
8803
Reid Spencer3da59db2006-11-27 01:05:10 +00008804 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008805 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8806 const Type *DstElTy = DstPTy->getElementType();
8807 const Type *SrcElTy = SrcPTy->getElementType();
8808
Nate Begeman83ad90a2008-03-31 00:22:16 +00008809 // If the address spaces don't match, don't eliminate the bitcast, which is
8810 // required for changing types.
8811 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8812 return 0;
8813
Victor Hernandez83d63912009-09-18 22:35:49 +00008814 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008815 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008816 // There is no need to modify malloc calls because it is their bitcast that
8817 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008818 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8819 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8820 return V;
8821
Chris Lattnerd717c182007-05-05 22:32:24 +00008822 // If the source and destination are pointers, and this cast is equivalent
8823 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008824 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008825 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008826 unsigned NumZeros = 0;
8827 while (SrcElTy != DstElTy &&
8828 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8829 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8830 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8831 ++NumZeros;
8832 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008833
Chris Lattnerd3e28342007-04-27 17:44:50 +00008834 // If we found a path from the src to dest, create the getelementptr now.
8835 if (SrcElTy == DstElTy) {
8836 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008837 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8838 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008839 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008840 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008841
Eli Friedman2451a642009-07-18 23:06:53 +00008842 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8843 if (DestVTy->getNumElements() == 1) {
8844 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008845 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008846 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008847 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008848 }
8849 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8850 }
8851 }
8852
8853 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8854 if (SrcVTy->getNumElements() == 1) {
8855 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008856 Value *Elem =
8857 Builder->CreateExtractElement(Src,
8858 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008859 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8860 }
8861 }
8862 }
8863
Reid Spencer3da59db2006-11-27 01:05:10 +00008864 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8865 if (SVI->hasOneUse()) {
8866 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8867 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008868 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008869 cast<VectorType>(DestTy)->getNumElements() ==
8870 SVI->getType()->getNumElements() &&
8871 SVI->getType()->getNumElements() ==
8872 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008873 CastInst *Tmp;
8874 // If either of the operands is a cast from CI.getType(), then
8875 // evaluating the shuffle in the casted destination's type will allow
8876 // us to eliminate at least one cast.
8877 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8878 Tmp->getOperand(0)->getType() == DestTy) ||
8879 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8880 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008881 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8882 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008883 // Return a new shuffle vector. Use the same element ID's, as we
8884 // know the vector types match #elts.
8885 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008886 }
8887 }
8888 }
8889 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008890 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008891}
8892
Chris Lattnere576b912004-04-09 23:46:01 +00008893/// GetSelectFoldableOperands - We want to turn code that looks like this:
8894/// %C = or %A, %B
8895/// %D = select %cond, %C, %A
8896/// into:
8897/// %C = select %cond, %B, 0
8898/// %D = or %A, %C
8899///
8900/// Assuming that the specified instruction is an operand to the select, return
8901/// a bitmask indicating which operands of this instruction are foldable if they
8902/// equal the other incoming value of the select.
8903///
8904static unsigned GetSelectFoldableOperands(Instruction *I) {
8905 switch (I->getOpcode()) {
8906 case Instruction::Add:
8907 case Instruction::Mul:
8908 case Instruction::And:
8909 case Instruction::Or:
8910 case Instruction::Xor:
8911 return 3; // Can fold through either operand.
8912 case Instruction::Sub: // Can only fold on the amount subtracted.
8913 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008914 case Instruction::LShr:
8915 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008916 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008917 default:
8918 return 0; // Cannot fold
8919 }
8920}
8921
8922/// GetSelectFoldableConstant - For the same transformation as the previous
8923/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008924static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008925 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008926 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008927 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008928 case Instruction::Add:
8929 case Instruction::Sub:
8930 case Instruction::Or:
8931 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008932 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008933 case Instruction::LShr:
8934 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008935 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008936 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008937 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008938 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008939 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008940 }
8941}
8942
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008943/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8944/// have the same opcode and only one use each. Try to simplify this.
8945Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8946 Instruction *FI) {
8947 if (TI->getNumOperands() == 1) {
8948 // If this is a non-volatile load or a cast from the same type,
8949 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008950 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008951 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8952 return 0;
8953 } else {
8954 return 0; // unknown unary op.
8955 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008956
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008957 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008958 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008959 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008960 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008961 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008962 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008963 }
8964
Reid Spencer832254e2007-02-02 02:16:23 +00008965 // Only handle binary operators here.
8966 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008967 return 0;
8968
8969 // Figure out if the operations have any operands in common.
8970 Value *MatchOp, *OtherOpT, *OtherOpF;
8971 bool MatchIsOpZero;
8972 if (TI->getOperand(0) == FI->getOperand(0)) {
8973 MatchOp = TI->getOperand(0);
8974 OtherOpT = TI->getOperand(1);
8975 OtherOpF = FI->getOperand(1);
8976 MatchIsOpZero = true;
8977 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8978 MatchOp = TI->getOperand(1);
8979 OtherOpT = TI->getOperand(0);
8980 OtherOpF = FI->getOperand(0);
8981 MatchIsOpZero = false;
8982 } else if (!TI->isCommutative()) {
8983 return 0;
8984 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8985 MatchOp = TI->getOperand(0);
8986 OtherOpT = TI->getOperand(1);
8987 OtherOpF = FI->getOperand(0);
8988 MatchIsOpZero = true;
8989 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8990 MatchOp = TI->getOperand(1);
8991 OtherOpT = TI->getOperand(0);
8992 OtherOpF = FI->getOperand(1);
8993 MatchIsOpZero = true;
8994 } else {
8995 return 0;
8996 }
8997
8998 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008999 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9000 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009001 InsertNewInstBefore(NewSI, SI);
9002
9003 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9004 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009005 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009006 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009007 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009008 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009009 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009010 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009011}
9012
Evan Chengde621922009-03-31 20:42:45 +00009013static bool isSelect01(Constant *C1, Constant *C2) {
9014 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9015 if (!C1I)
9016 return false;
9017 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9018 if (!C2I)
9019 return false;
9020 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9021}
9022
9023/// FoldSelectIntoOp - Try fold the select into one of the operands to
9024/// facilitate further optimization.
9025Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9026 Value *FalseVal) {
9027 // See the comment above GetSelectFoldableOperands for a description of the
9028 // transformation we are doing here.
9029 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9030 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9031 !isa<Constant>(FalseVal)) {
9032 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9033 unsigned OpToFold = 0;
9034 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9035 OpToFold = 1;
9036 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9037 OpToFold = 2;
9038 }
9039
9040 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009041 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009042 Value *OOp = TVI->getOperand(2-OpToFold);
9043 // Avoid creating select between 2 constants unless it's selecting
9044 // between 0 and 1.
9045 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9046 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9047 InsertNewInstBefore(NewSel, SI);
9048 NewSel->takeName(TVI);
9049 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9050 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009051 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009052 }
9053 }
9054 }
9055 }
9056 }
9057
9058 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9059 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9060 !isa<Constant>(TrueVal)) {
9061 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9062 unsigned OpToFold = 0;
9063 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9064 OpToFold = 1;
9065 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9066 OpToFold = 2;
9067 }
9068
9069 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009070 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009071 Value *OOp = FVI->getOperand(2-OpToFold);
9072 // Avoid creating select between 2 constants unless it's selecting
9073 // between 0 and 1.
9074 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9075 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9076 InsertNewInstBefore(NewSel, SI);
9077 NewSel->takeName(FVI);
9078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9079 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009080 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009081 }
9082 }
9083 }
9084 }
9085 }
9086
9087 return 0;
9088}
9089
Dan Gohman81b28ce2008-09-16 18:46:06 +00009090/// visitSelectInstWithICmp - Visit a SelectInst that has an
9091/// ICmpInst as its first operand.
9092///
9093Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9094 ICmpInst *ICI) {
9095 bool Changed = false;
9096 ICmpInst::Predicate Pred = ICI->getPredicate();
9097 Value *CmpLHS = ICI->getOperand(0);
9098 Value *CmpRHS = ICI->getOperand(1);
9099 Value *TrueVal = SI.getTrueValue();
9100 Value *FalseVal = SI.getFalseValue();
9101
9102 // Check cases where the comparison is with a constant that
9103 // can be adjusted to fit the min/max idiom. We may edit ICI in
9104 // place here, so make sure the select is the only user.
9105 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009106 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009107 switch (Pred) {
9108 default: break;
9109 case ICmpInst::ICMP_ULT:
9110 case ICmpInst::ICMP_SLT: {
9111 // X < MIN ? T : F --> F
9112 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9113 return ReplaceInstUsesWith(SI, FalseVal);
9114 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009115 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009116 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9117 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9118 Pred = ICmpInst::getSwappedPredicate(Pred);
9119 CmpRHS = AdjustedRHS;
9120 std::swap(FalseVal, TrueVal);
9121 ICI->setPredicate(Pred);
9122 ICI->setOperand(1, CmpRHS);
9123 SI.setOperand(1, TrueVal);
9124 SI.setOperand(2, FalseVal);
9125 Changed = true;
9126 }
9127 break;
9128 }
9129 case ICmpInst::ICMP_UGT:
9130 case ICmpInst::ICMP_SGT: {
9131 // X > MAX ? T : F --> F
9132 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9133 return ReplaceInstUsesWith(SI, FalseVal);
9134 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009135 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009136 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9137 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9138 Pred = ICmpInst::getSwappedPredicate(Pred);
9139 CmpRHS = AdjustedRHS;
9140 std::swap(FalseVal, TrueVal);
9141 ICI->setPredicate(Pred);
9142 ICI->setOperand(1, CmpRHS);
9143 SI.setOperand(1, TrueVal);
9144 SI.setOperand(2, FalseVal);
9145 Changed = true;
9146 }
9147 break;
9148 }
9149 }
9150
Dan Gohman1975d032008-10-30 20:40:10 +00009151 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9152 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009153 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009154 if (match(TrueVal, m_ConstantInt<-1>()) &&
9155 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009156 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009157 else if (match(TrueVal, m_ConstantInt<0>()) &&
9158 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009159 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9160
Dan Gohman1975d032008-10-30 20:40:10 +00009161 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9162 // If we are just checking for a icmp eq of a single bit and zext'ing it
9163 // to an integer, then shift the bit to the appropriate place and then
9164 // cast to integer to avoid the comparison.
9165 const APInt &Op1CV = CI->getValue();
9166
9167 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9168 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9169 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009170 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009171 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009172 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009173 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009174 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009175 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009176 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009177 if (In->getType() != SI.getType())
9178 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009179 true/*SExt*/, "tmp", ICI);
9180
9181 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009182 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009183 In->getName()+".not"), *ICI);
9184
9185 return ReplaceInstUsesWith(SI, In);
9186 }
9187 }
9188 }
9189
Dan Gohman81b28ce2008-09-16 18:46:06 +00009190 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9191 // Transform (X == Y) ? X : Y -> Y
9192 if (Pred == ICmpInst::ICMP_EQ)
9193 return ReplaceInstUsesWith(SI, FalseVal);
9194 // Transform (X != Y) ? X : Y -> X
9195 if (Pred == ICmpInst::ICMP_NE)
9196 return ReplaceInstUsesWith(SI, TrueVal);
9197 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9198
9199 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9200 // Transform (X == Y) ? Y : X -> X
9201 if (Pred == ICmpInst::ICMP_EQ)
9202 return ReplaceInstUsesWith(SI, FalseVal);
9203 // Transform (X != Y) ? Y : X -> Y
9204 if (Pred == ICmpInst::ICMP_NE)
9205 return ReplaceInstUsesWith(SI, TrueVal);
9206 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9207 }
9208
9209 /// NOTE: if we wanted to, this is where to detect integer ABS
9210
9211 return Changed ? &SI : 0;
9212}
9213
Chris Lattner3d69f462004-03-12 05:52:32 +00009214Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009215 Value *CondVal = SI.getCondition();
9216 Value *TrueVal = SI.getTrueValue();
9217 Value *FalseVal = SI.getFalseValue();
9218
9219 // select true, X, Y -> X
9220 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009221 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009222 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009223
9224 // select C, X, X -> X
9225 if (TrueVal == FalseVal)
9226 return ReplaceInstUsesWith(SI, TrueVal);
9227
Chris Lattnere87597f2004-10-16 18:11:37 +00009228 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9229 return ReplaceInstUsesWith(SI, FalseVal);
9230 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9231 return ReplaceInstUsesWith(SI, TrueVal);
9232 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9233 if (isa<Constant>(TrueVal))
9234 return ReplaceInstUsesWith(SI, TrueVal);
9235 else
9236 return ReplaceInstUsesWith(SI, FalseVal);
9237 }
9238
Owen Anderson1d0be152009-08-13 21:58:54 +00009239 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009240 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009241 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009242 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009243 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009244 } else {
9245 // Change: A = select B, false, C --> A = and !B, C
9246 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009247 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009248 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009249 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009250 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009251 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009252 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009253 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009254 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009255 } else {
9256 // Change: A = select B, C, true --> A = or !B, C
9257 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009258 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009259 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009260 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009261 }
9262 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009263
9264 // select a, b, a -> a&b
9265 // select a, a, b -> a|b
9266 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009267 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009268 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009269 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009270 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009271
Chris Lattner2eefe512004-04-09 19:05:30 +00009272 // Selecting between two integer constants?
9273 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9274 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009275 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009276 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009277 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009278 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009279 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009280 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009281 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009282 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009283 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009284 }
Chris Lattner457dd822004-06-09 07:59:58 +00009285
Reid Spencere4d87aa2006-12-23 06:05:41 +00009286 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009287 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009288 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009289 // non-constant value, eliminate this whole mess. This corresponds to
9290 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009291 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009292 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009293 cast<Constant>(IC->getOperand(1))->isNullValue())
9294 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9295 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009296 isa<ConstantInt>(ICA->getOperand(1)) &&
9297 (ICA->getOperand(1) == TrueValC ||
9298 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009299 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9300 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009301 // know whether we have a icmp_ne or icmp_eq and whether the
9302 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009303 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009304 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009305 Value *V = ICA;
9306 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009307 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009308 Instruction::Xor, V, ICA->getOperand(1)), SI);
9309 return ReplaceInstUsesWith(SI, V);
9310 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009311 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009312 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009313
9314 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009315 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9316 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009317 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009318 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9319 // This is not safe in general for floating point:
9320 // consider X== -0, Y== +0.
9321 // It becomes safe if either operand is a nonzero constant.
9322 ConstantFP *CFPt, *CFPf;
9323 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9324 !CFPt->getValueAPF().isZero()) ||
9325 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9326 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009327 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009328 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009329 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009330 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009331 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009332 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009333
Reid Spencere4d87aa2006-12-23 06:05:41 +00009334 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009335 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009336 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9337 // This is not safe in general for floating point:
9338 // consider X== -0, Y== +0.
9339 // It becomes safe if either operand is a nonzero constant.
9340 ConstantFP *CFPt, *CFPf;
9341 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9342 !CFPt->getValueAPF().isZero()) ||
9343 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9344 !CFPf->getValueAPF().isZero()))
9345 return ReplaceInstUsesWith(SI, FalseVal);
9346 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009347 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009348 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9349 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009350 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009351 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009352 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009353 }
9354
9355 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009356 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9357 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9358 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009359
Chris Lattner87875da2005-01-13 22:52:24 +00009360 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9361 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9362 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009363 Instruction *AddOp = 0, *SubOp = 0;
9364
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009365 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9366 if (TI->getOpcode() == FI->getOpcode())
9367 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9368 return IV;
9369
9370 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9371 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009372 if ((TI->getOpcode() == Instruction::Sub &&
9373 FI->getOpcode() == Instruction::Add) ||
9374 (TI->getOpcode() == Instruction::FSub &&
9375 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009376 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009377 } else if ((FI->getOpcode() == Instruction::Sub &&
9378 TI->getOpcode() == Instruction::Add) ||
9379 (FI->getOpcode() == Instruction::FSub &&
9380 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009381 AddOp = TI; SubOp = FI;
9382 }
9383
9384 if (AddOp) {
9385 Value *OtherAddOp = 0;
9386 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9387 OtherAddOp = AddOp->getOperand(1);
9388 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9389 OtherAddOp = AddOp->getOperand(0);
9390 }
9391
9392 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009393 // So at this point we know we have (Y -> OtherAddOp):
9394 // select C, (add X, Y), (sub X, Z)
9395 Value *NegVal; // Compute -Z
9396 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009397 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009398 } else {
9399 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009400 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009401 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009402 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009403
9404 Value *NewTrueOp = OtherAddOp;
9405 Value *NewFalseOp = NegVal;
9406 if (AddOp != TI)
9407 std::swap(NewTrueOp, NewFalseOp);
9408 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009409 SelectInst::Create(CondVal, NewTrueOp,
9410 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009411
9412 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009413 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009414 }
9415 }
9416 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009417
Chris Lattnere576b912004-04-09 23:46:01 +00009418 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009419 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009420 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9421 if (FoldI)
9422 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009423 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009424
9425 if (BinaryOperator::isNot(CondVal)) {
9426 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9427 SI.setOperand(1, FalseVal);
9428 SI.setOperand(2, TrueVal);
9429 return &SI;
9430 }
9431
Chris Lattner3d69f462004-03-12 05:52:32 +00009432 return 0;
9433}
9434
Dan Gohmaneee962e2008-04-10 18:43:06 +00009435/// EnforceKnownAlignment - If the specified pointer points to an object that
9436/// we control, modify the object's alignment to PrefAlign. This isn't
9437/// often possible though. If alignment is important, a more reliable approach
9438/// is to simply align all global variables and allocation instructions to
9439/// their preferred alignment from the beginning.
9440///
9441static unsigned EnforceKnownAlignment(Value *V,
9442 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009443
Dan Gohmaneee962e2008-04-10 18:43:06 +00009444 User *U = dyn_cast<User>(V);
9445 if (!U) return Align;
9446
Dan Gohmanca178902009-07-17 20:47:02 +00009447 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009448 default: break;
9449 case Instruction::BitCast:
9450 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9451 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009452 // If all indexes are zero, it is just the alignment of the base pointer.
9453 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009454 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009455 if (!isa<Constant>(*i) ||
9456 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009457 AllZeroOperands = false;
9458 break;
9459 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009460
9461 if (AllZeroOperands) {
9462 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009463 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009464 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009465 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009466 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009467 }
9468
9469 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9470 // If there is a large requested alignment and we can, bump up the alignment
9471 // of the global.
9472 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009473 if (GV->getAlignment() >= PrefAlign)
9474 Align = GV->getAlignment();
9475 else {
9476 GV->setAlignment(PrefAlign);
9477 Align = PrefAlign;
9478 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009479 }
9480 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9481 // If there is a requested alignment and if this is an alloca, round up. We
9482 // don't do this for malloc, because some systems can't respect the request.
9483 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009484 if (AI->getAlignment() >= PrefAlign)
9485 Align = AI->getAlignment();
9486 else {
9487 AI->setAlignment(PrefAlign);
9488 Align = PrefAlign;
9489 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009490 }
Victor Hernandez83d63912009-09-18 22:35:49 +00009491 // No alignment changes are possible for malloc calls
Dan Gohmaneee962e2008-04-10 18:43:06 +00009492 }
9493
9494 return Align;
9495}
9496
9497/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9498/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9499/// and it is more than the alignment of the ultimate object, see if we can
9500/// increase the alignment of the ultimate object, making this check succeed.
9501unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9502 unsigned PrefAlign) {
9503 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9504 sizeof(PrefAlign) * CHAR_BIT;
9505 APInt Mask = APInt::getAllOnesValue(BitWidth);
9506 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9507 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9508 unsigned TrailZ = KnownZero.countTrailingOnes();
9509 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9510
9511 if (PrefAlign > Align)
9512 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9513
9514 // We don't need to make any adjustment.
9515 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009516}
9517
Chris Lattnerf497b022008-01-13 23:50:23 +00009518Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009519 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009520 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009521 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009522 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009523
9524 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009525 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009526 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009527 return MI;
9528 }
9529
9530 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9531 // load/store.
9532 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9533 if (MemOpLength == 0) return 0;
9534
Chris Lattner37ac6082008-01-14 00:28:35 +00009535 // Source and destination pointer types are always "i8*" for intrinsic. See
9536 // if the size is something we can handle with a single primitive load/store.
9537 // A single load+store correctly handles overlapping memory in the memmove
9538 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009539 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009540 if (Size == 0) return MI; // Delete this mem transfer.
9541
9542 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009543 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009544
Chris Lattner37ac6082008-01-14 00:28:35 +00009545 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009546 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009547 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009548
9549 // Memcpy forces the use of i8* for the source and destination. That means
9550 // that if you're using memcpy to move one double around, you'll get a cast
9551 // from double* to i8*. We'd much rather use a double load+store rather than
9552 // an i64 load+store, here because this improves the odds that the source or
9553 // dest address will be promotable. See if we can find a better type than the
9554 // integer datatype.
9555 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9556 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009557 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009558 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9559 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009560 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009561 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9562 if (STy->getNumElements() == 1)
9563 SrcETy = STy->getElementType(0);
9564 else
9565 break;
9566 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9567 if (ATy->getNumElements() == 1)
9568 SrcETy = ATy->getElementType();
9569 else
9570 break;
9571 } else
9572 break;
9573 }
9574
Dan Gohman8f8e2692008-05-23 01:52:21 +00009575 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009576 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009577 }
9578 }
9579
9580
Chris Lattnerf497b022008-01-13 23:50:23 +00009581 // If the memcpy/memmove provides better alignment info than we can
9582 // infer, use it.
9583 SrcAlign = std::max(SrcAlign, CopyAlign);
9584 DstAlign = std::max(DstAlign, CopyAlign);
9585
Chris Lattner08142f22009-08-30 19:47:22 +00009586 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9587 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009588 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9589 InsertNewInstBefore(L, *MI);
9590 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9591
9592 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009593 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009594 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009595}
Chris Lattner3d69f462004-03-12 05:52:32 +00009596
Chris Lattner69ea9d22008-04-30 06:39:11 +00009597Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9598 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009599 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009600 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009601 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009602 return MI;
9603 }
9604
9605 // Extract the length and alignment and fill if they are constant.
9606 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9607 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009608 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009609 return 0;
9610 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009611 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009612
9613 // If the length is zero, this is a no-op
9614 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9615
9616 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9617 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009618 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009619
9620 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009621 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009622
9623 // Alignment 0 is identity for alignment 1 for memset, but not store.
9624 if (Alignment == 0) Alignment = 1;
9625
9626 // Extract the fill value and store.
9627 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009628 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009629 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009630
9631 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009632 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009633 return MI;
9634 }
9635
9636 return 0;
9637}
9638
9639
Chris Lattner8b0ea312006-01-13 20:11:04 +00009640/// visitCallInst - CallInst simplification. This mostly only handles folding
9641/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9642/// the heavy lifting.
9643///
Chris Lattner9fe38862003-06-19 17:00:31 +00009644Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009645 // If the caller function is nounwind, mark the call as nounwind, even if the
9646 // callee isn't.
9647 if (CI.getParent()->getParent()->doesNotThrow() &&
9648 !CI.doesNotThrow()) {
9649 CI.setDoesNotThrow();
9650 return &CI;
9651 }
9652
Chris Lattner8b0ea312006-01-13 20:11:04 +00009653 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9654 if (!II) return visitCallSite(&CI);
9655
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009656 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9657 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009658 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009659 bool Changed = false;
9660
9661 // memmove/cpy/set of zero bytes is a noop.
9662 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9663 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9664
Chris Lattner35b9e482004-10-12 04:52:52 +00009665 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009666 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009667 // Replace the instruction with just byte operations. We would
9668 // transform other cases to loads/stores, but we don't know if
9669 // alignment is sufficient.
9670 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009671 }
9672
Chris Lattner35b9e482004-10-12 04:52:52 +00009673 // If we have a memmove and the source operation is a constant global,
9674 // then the source and dest pointers can't alias, so we can change this
9675 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009676 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009677 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9678 if (GVSrc->isConstant()) {
9679 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009680 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9681 const Type *Tys[1];
9682 Tys[0] = CI.getOperand(3)->getType();
9683 CI.setOperand(0,
9684 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009685 Changed = true;
9686 }
Chris Lattnera935db82008-05-28 05:30:41 +00009687
9688 // memmove(x,x,size) -> noop.
9689 if (MMI->getSource() == MMI->getDest())
9690 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009691 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009692
Chris Lattner95a959d2006-03-06 20:18:44 +00009693 // If we can determine a pointer alignment that is bigger than currently
9694 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009695 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009696 if (Instruction *I = SimplifyMemTransfer(MI))
9697 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009698 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9699 if (Instruction *I = SimplifyMemSet(MSI))
9700 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009701 }
9702
Chris Lattner8b0ea312006-01-13 20:11:04 +00009703 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009704 }
9705
9706 switch (II->getIntrinsicID()) {
9707 default: break;
9708 case Intrinsic::bswap:
9709 // bswap(bswap(x)) -> x
9710 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9711 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9712 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9713 break;
9714 case Intrinsic::ppc_altivec_lvx:
9715 case Intrinsic::ppc_altivec_lvxl:
9716 case Intrinsic::x86_sse_loadu_ps:
9717 case Intrinsic::x86_sse2_loadu_pd:
9718 case Intrinsic::x86_sse2_loadu_dq:
9719 // Turn PPC lvx -> load if the pointer is known aligned.
9720 // Turn X86 loadups -> load if the pointer is known aligned.
9721 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009722 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9723 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009724 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009725 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009726 break;
9727 case Intrinsic::ppc_altivec_stvx:
9728 case Intrinsic::ppc_altivec_stvxl:
9729 // Turn stvx -> store if the pointer is known aligned.
9730 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9731 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009732 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009733 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009734 return new StoreInst(II->getOperand(1), Ptr);
9735 }
9736 break;
9737 case Intrinsic::x86_sse_storeu_ps:
9738 case Intrinsic::x86_sse2_storeu_pd:
9739 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009740 // Turn X86 storeu -> store if the pointer is known aligned.
9741 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9742 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009743 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009744 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009745 return new StoreInst(II->getOperand(2), Ptr);
9746 }
9747 break;
9748
9749 case Intrinsic::x86_sse_cvttss2si: {
9750 // These intrinsics only demands the 0th element of its input vector. If
9751 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009752 unsigned VWidth =
9753 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9754 APInt DemandedElts(VWidth, 1);
9755 APInt UndefElts(VWidth, 0);
9756 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009757 UndefElts)) {
9758 II->setOperand(1, V);
9759 return II;
9760 }
9761 break;
9762 }
9763
9764 case Intrinsic::ppc_altivec_vperm:
9765 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9766 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9767 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009768
Chris Lattner0521e3c2008-06-18 04:33:20 +00009769 // Check that all of the elements are integer constants or undefs.
9770 bool AllEltsOk = true;
9771 for (unsigned i = 0; i != 16; ++i) {
9772 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9773 !isa<UndefValue>(Mask->getOperand(i))) {
9774 AllEltsOk = false;
9775 break;
9776 }
9777 }
9778
9779 if (AllEltsOk) {
9780 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009781 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9782 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009783 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009784
Chris Lattner0521e3c2008-06-18 04:33:20 +00009785 // Only extract each element once.
9786 Value *ExtractedElts[32];
9787 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9788
Chris Lattnere2ed0572006-04-06 19:19:17 +00009789 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009790 if (isa<UndefValue>(Mask->getOperand(i)))
9791 continue;
9792 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9793 Idx &= 31; // Match the hardware behavior.
9794
9795 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009796 ExtractedElts[Idx] =
9797 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9798 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9799 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009800 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009801
Chris Lattner0521e3c2008-06-18 04:33:20 +00009802 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009803 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9804 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9805 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009806 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009807 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009808 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009809 }
9810 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009811
Chris Lattner0521e3c2008-06-18 04:33:20 +00009812 case Intrinsic::stackrestore: {
9813 // If the save is right next to the restore, remove the restore. This can
9814 // happen when variable allocas are DCE'd.
9815 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9816 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9817 BasicBlock::iterator BI = SS;
9818 if (&*++BI == II)
9819 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009820 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009821 }
9822
9823 // Scan down this block to see if there is another stack restore in the
9824 // same block without an intervening call/alloca.
9825 BasicBlock::iterator BI = II;
9826 TerminatorInst *TI = II->getParent()->getTerminator();
9827 bool CannotRemove = false;
9828 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009829 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009830 CannotRemove = true;
9831 break;
9832 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009833 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9834 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9835 // If there is a stackrestore below this one, remove this one.
9836 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9837 return EraseInstFromFunction(CI);
9838 // Otherwise, ignore the intrinsic.
9839 } else {
9840 // If we found a non-intrinsic call, we can't remove the stack
9841 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009842 CannotRemove = true;
9843 break;
9844 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009845 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009846 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009847
9848 // If the stack restore is in a return/unwind block and if there are no
9849 // allocas or calls between the restore and the return, nuke the restore.
9850 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9851 return EraseInstFromFunction(CI);
9852 break;
9853 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009854 }
9855
Chris Lattner8b0ea312006-01-13 20:11:04 +00009856 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009857}
9858
9859// InvokeInst simplification
9860//
9861Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009862 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009863}
9864
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009865/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9866/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009867static bool isSafeToEliminateVarargsCast(const CallSite CS,
9868 const CastInst * const CI,
9869 const TargetData * const TD,
9870 const int ix) {
9871 if (!CI->isLosslessCast())
9872 return false;
9873
9874 // The size of ByVal arguments is derived from the type, so we
9875 // can't change to a type with a different size. If the size were
9876 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009877 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009878 return true;
9879
9880 const Type* SrcTy =
9881 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9882 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9883 if (!SrcTy->isSized() || !DstTy->isSized())
9884 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009885 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009886 return false;
9887 return true;
9888}
9889
Chris Lattnera44d8a22003-10-07 22:32:43 +00009890// visitCallSite - Improvements for call and invoke instructions.
9891//
9892Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009893 bool Changed = false;
9894
9895 // If the callee is a constexpr cast of a function, attempt to move the cast
9896 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009897 if (transformConstExprCastCall(CS)) return 0;
9898
Chris Lattner6c266db2003-10-07 22:54:13 +00009899 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009900
Chris Lattner08b22ec2005-05-13 07:09:09 +00009901 if (Function *CalleeF = dyn_cast<Function>(Callee))
9902 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9903 Instruction *OldCall = CS.getInstruction();
9904 // If the call and callee calling conventions don't match, this call must
9905 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009906 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009907 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009908 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009909 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009910 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009911 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9912 return EraseInstFromFunction(*OldCall);
9913 return 0;
9914 }
9915
Chris Lattner17be6352004-10-18 02:59:09 +00009916 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9917 // This instruction is not reachable, just remove it. We insert a store to
9918 // undef so that we know that this code is not reachable, despite the fact
9919 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009920 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009921 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009922 CS.getInstruction());
9923
9924 if (!CS.getInstruction()->use_empty())
9925 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009926 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009927
9928 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9929 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009930 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009931 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009932 }
Chris Lattner17be6352004-10-18 02:59:09 +00009933 return EraseInstFromFunction(*CS.getInstruction());
9934 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009935
Duncan Sandscdb6d922007-09-17 10:26:40 +00009936 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9937 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9938 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9939 return transformCallThroughTrampoline(CS);
9940
Chris Lattner6c266db2003-10-07 22:54:13 +00009941 const PointerType *PTy = cast<PointerType>(Callee->getType());
9942 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9943 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009944 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009945 // See if we can optimize any arguments passed through the varargs area of
9946 // the call.
9947 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009948 E = CS.arg_end(); I != E; ++I, ++ix) {
9949 CastInst *CI = dyn_cast<CastInst>(*I);
9950 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9951 *I = CI->getOperand(0);
9952 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009953 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009954 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009955 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009956
Duncan Sandsf0c33542007-12-19 21:13:37 +00009957 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009958 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009959 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009960 Changed = true;
9961 }
9962
Chris Lattner6c266db2003-10-07 22:54:13 +00009963 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009964}
9965
Chris Lattner9fe38862003-06-19 17:00:31 +00009966// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9967// attempt to move the cast to the arguments of the call/invoke.
9968//
9969bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9970 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9971 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009972 if (CE->getOpcode() != Instruction::BitCast ||
9973 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009974 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009975 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009976 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009977 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009978
9979 // Okay, this is a cast from a function to a different type. Unless doing so
9980 // would cause a type conversion of one of our arguments, change this call to
9981 // be a direct call with arguments casted to the appropriate types.
9982 //
9983 const FunctionType *FT = Callee->getFunctionType();
9984 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009985 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009986
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009987 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009988 return false; // TODO: Handle multiple return values.
9989
Chris Lattnerf78616b2004-01-14 06:06:08 +00009990 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009991 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009992 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009993 // Conversion is ok if changing from one pointer type to another or from
9994 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009995 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009996 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009997 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009998 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00009999 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010000
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010001 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010002 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010003 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010004 return false; // Cannot transform this return value.
10005
Chris Lattner58d74912008-03-12 17:45:29 +000010006 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010007 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010008 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010009 return false; // Attribute not compatible with transformed value.
10010 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010011
Chris Lattnerf78616b2004-01-14 06:06:08 +000010012 // If the callsite is an invoke instruction, and the return value is used by
10013 // a PHI node in a successor, we cannot change the return type of the call
10014 // because there is no place to put the cast instruction (without breaking
10015 // the critical edge). Bail out in this case.
10016 if (!Caller->use_empty())
10017 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10018 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10019 UI != E; ++UI)
10020 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10021 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010022 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010023 return false;
10024 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010025
10026 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10027 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010028
Chris Lattner9fe38862003-06-19 17:00:31 +000010029 CallSite::arg_iterator AI = CS.arg_begin();
10030 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10031 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010032 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010033
10034 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010035 return false; // Cannot transform this parameter value.
10036
Devang Patel19c87462008-09-26 22:53:05 +000010037 if (CallerPAL.getParamAttributes(i + 1)
10038 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010039 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010040
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010041 // Converting from one pointer type to another or between a pointer and an
10042 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010043 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010044 (TD && ((isa<PointerType>(ParamTy) ||
10045 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10046 (isa<PointerType>(ActTy) ||
10047 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010048 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010049 }
10050
10051 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010052 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010053 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010054
Chris Lattner58d74912008-03-12 17:45:29 +000010055 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10056 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010057 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010058 // won't be dropping them. Check that these extra arguments have attributes
10059 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010060 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10061 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010062 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010063 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010064 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010065 return false;
10066 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010067
Chris Lattner9fe38862003-06-19 17:00:31 +000010068 // Okay, we decided that this is a safe thing to do: go ahead and start
10069 // inserting cast instructions as necessary...
10070 std::vector<Value*> Args;
10071 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010072 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010073 attrVec.reserve(NumCommonArgs);
10074
10075 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010076 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010077
10078 // If the return value is not being used, the type may not be compatible
10079 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010080 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010081
10082 // Add the new return attributes.
10083 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010084 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010085
10086 AI = CS.arg_begin();
10087 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10088 const Type *ParamTy = FT->getParamType(i);
10089 if ((*AI)->getType() == ParamTy) {
10090 Args.push_back(*AI);
10091 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010092 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010093 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010094 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010095 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010096
10097 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010098 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010099 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010100 }
10101
10102 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010103 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010104 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010105 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010106
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010107 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010108 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010109 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010110 errs() << "WARNING: While resolving call to function '"
10111 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010112 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010113 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010114 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10115 const Type *PTy = getPromotedType((*AI)->getType());
10116 if (PTy != (*AI)->getType()) {
10117 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010118 Instruction::CastOps opcode =
10119 CastInst::getCastOpcode(*AI, false, PTy, false);
10120 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010121 } else {
10122 Args.push_back(*AI);
10123 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010124
Duncan Sandse1e520f2008-01-13 08:02:44 +000010125 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010126 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010127 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010128 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010129 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010130 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010131
Devang Patel19c87462008-09-26 22:53:05 +000010132 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10133 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10134
Owen Anderson1d0be152009-08-13 21:58:54 +000010135 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010136 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010137
Eric Christophera66297a2009-07-25 02:45:27 +000010138 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10139 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010140
Chris Lattner9fe38862003-06-19 17:00:31 +000010141 Instruction *NC;
10142 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010143 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010144 Args.begin(), Args.end(),
10145 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010146 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010147 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010148 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010149 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10150 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010151 CallInst *CI = cast<CallInst>(Caller);
10152 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010153 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010154 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010155 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010156 }
10157
Chris Lattner6934a042007-02-11 01:23:03 +000010158 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010159 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010160 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010161 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010162 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010163 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010164 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010165
10166 // If this is an invoke instruction, we should insert it after the first
10167 // non-phi, instruction in the normal successor block.
10168 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010169 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010170 InsertNewInstBefore(NC, *I);
10171 } else {
10172 // Otherwise, it's a call, just insert cast right after the call instr
10173 InsertNewInstBefore(NC, *Caller);
10174 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010175 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010176 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010177 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010178 }
10179 }
10180
Chris Lattner931f8f32009-08-31 05:17:58 +000010181
10182 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010183 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010184
10185 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010186 return true;
10187}
10188
Duncan Sandscdb6d922007-09-17 10:26:40 +000010189// transformCallThroughTrampoline - Turn a call to a function created by the
10190// init_trampoline intrinsic into a direct call to the underlying function.
10191//
10192Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10193 Value *Callee = CS.getCalledValue();
10194 const PointerType *PTy = cast<PointerType>(Callee->getType());
10195 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010196 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010197
10198 // If the call already has the 'nest' attribute somewhere then give up -
10199 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010200 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010201 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010202
10203 IntrinsicInst *Tramp =
10204 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10205
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010206 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010207 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10208 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10209
Devang Patel05988662008-09-25 21:00:45 +000010210 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010211 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010212 unsigned NestIdx = 1;
10213 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010214 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010215
10216 // Look for a parameter marked with the 'nest' attribute.
10217 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10218 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010219 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010220 // Record the parameter type and any other attributes.
10221 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010222 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010223 break;
10224 }
10225
10226 if (NestTy) {
10227 Instruction *Caller = CS.getInstruction();
10228 std::vector<Value*> NewArgs;
10229 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10230
Devang Patel05988662008-09-25 21:00:45 +000010231 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010232 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010233
Duncan Sandscdb6d922007-09-17 10:26:40 +000010234 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010235 // mean appending it. Likewise for attributes.
10236
Devang Patel19c87462008-09-26 22:53:05 +000010237 // Add any result attributes.
10238 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010239 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010240
Duncan Sandscdb6d922007-09-17 10:26:40 +000010241 {
10242 unsigned Idx = 1;
10243 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10244 do {
10245 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010246 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010247 Value *NestVal = Tramp->getOperand(3);
10248 if (NestVal->getType() != NestTy)
10249 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10250 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010251 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010252 }
10253
10254 if (I == E)
10255 break;
10256
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010257 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010258 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010259 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010260 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010261 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010262
10263 ++Idx, ++I;
10264 } while (1);
10265 }
10266
Devang Patel19c87462008-09-26 22:53:05 +000010267 // Add any function attributes.
10268 if (Attributes Attr = Attrs.getFnAttributes())
10269 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10270
Duncan Sandscdb6d922007-09-17 10:26:40 +000010271 // The trampoline may have been bitcast to a bogus type (FTy).
10272 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010273 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010274
Duncan Sandscdb6d922007-09-17 10:26:40 +000010275 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010276 NewTypes.reserve(FTy->getNumParams()+1);
10277
Duncan Sandscdb6d922007-09-17 10:26:40 +000010278 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010279 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010280 {
10281 unsigned Idx = 1;
10282 FunctionType::param_iterator I = FTy->param_begin(),
10283 E = FTy->param_end();
10284
10285 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010286 if (Idx == NestIdx)
10287 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010288 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010289
10290 if (I == E)
10291 break;
10292
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010293 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010294 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010295
10296 ++Idx, ++I;
10297 } while (1);
10298 }
10299
10300 // Replace the trampoline call with a direct call. Let the generic
10301 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010302 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010303 FTy->isVarArg());
10304 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010305 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010306 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010307 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010308 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10309 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010310
10311 Instruction *NewCaller;
10312 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010313 NewCaller = InvokeInst::Create(NewCallee,
10314 II->getNormalDest(), II->getUnwindDest(),
10315 NewArgs.begin(), NewArgs.end(),
10316 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010317 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010318 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010319 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010320 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10321 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010322 if (cast<CallInst>(Caller)->isTailCall())
10323 cast<CallInst>(NewCaller)->setTailCall();
10324 cast<CallInst>(NewCaller)->
10325 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010326 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010327 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010328 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010329 Caller->replaceAllUsesWith(NewCaller);
10330 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010331 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010332 return 0;
10333 }
10334 }
10335
10336 // Replace the trampoline call with a direct call. Since there is no 'nest'
10337 // parameter, there is no need to adjust the argument list. Let the generic
10338 // code sort out any function type mismatches.
10339 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010340 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010341 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010342 CS.setCalledFunction(NewCallee);
10343 return CS.getInstruction();
10344}
10345
Dan Gohman9ad29202009-09-16 16:50:24 +000010346/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10347/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010348/// and a single binop.
10349Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10350 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010351 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010352 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010353 Value *LHSVal = FirstInst->getOperand(0);
10354 Value *RHSVal = FirstInst->getOperand(1);
10355
10356 const Type *LHSType = LHSVal->getType();
10357 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010358
Dan Gohman9ad29202009-09-16 16:50:24 +000010359 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010360 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010361 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010362 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010363 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010364 // types or GEP's with different index types.
10365 I->getOperand(0)->getType() != LHSType ||
10366 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010367 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010368
10369 // If they are CmpInst instructions, check their predicates
10370 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10371 if (cast<CmpInst>(I)->getPredicate() !=
10372 cast<CmpInst>(FirstInst)->getPredicate())
10373 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010374
10375 // Keep track of which operand needs a phi node.
10376 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10377 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010378 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010379
10380 // If both LHS and RHS would need a PHI, don't do this transformation,
10381 // because it would increase the number of PHIs entering the block,
10382 // which leads to higher register pressure. This is especially
10383 // bad when the PHIs are in the header of a loop.
10384 if (!LHSVal && !RHSVal)
10385 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010386
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010387 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010388
Chris Lattner7da52b22006-11-01 04:51:18 +000010389 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010390 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010391 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010392 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010393 NewLHS = PHINode::Create(LHSType,
10394 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010395 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10396 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010397 InsertNewInstBefore(NewLHS, PN);
10398 LHSVal = NewLHS;
10399 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010400
10401 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010402 NewRHS = PHINode::Create(RHSType,
10403 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010404 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10405 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010406 InsertNewInstBefore(NewRHS, PN);
10407 RHSVal = NewRHS;
10408 }
10409
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010410 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010411 if (NewLHS || NewRHS) {
10412 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10413 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10414 if (NewLHS) {
10415 Value *NewInLHS = InInst->getOperand(0);
10416 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10417 }
10418 if (NewRHS) {
10419 Value *NewInRHS = InInst->getOperand(1);
10420 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10421 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010422 }
10423 }
10424
Chris Lattner7da52b22006-11-01 04:51:18 +000010425 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010426 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010427 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010428 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010429 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010430}
10431
Chris Lattner05f18922008-12-01 02:34:36 +000010432Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10433 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10434
10435 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10436 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010437 // This is true if all GEP bases are allocas and if all indices into them are
10438 // constants.
10439 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010440
10441 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010442 // more than one phi, which leads to higher register pressure. This is
10443 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010444 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010445
Dan Gohman9ad29202009-09-16 16:50:24 +000010446 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010447 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10448 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10449 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10450 GEP->getNumOperands() != FirstInst->getNumOperands())
10451 return 0;
10452
Chris Lattner36d3e322009-02-21 00:46:50 +000010453 // Keep track of whether or not all GEPs are of alloca pointers.
10454 if (AllBasePointersAreAllocas &&
10455 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10456 !GEP->hasAllConstantIndices()))
10457 AllBasePointersAreAllocas = false;
10458
Chris Lattner05f18922008-12-01 02:34:36 +000010459 // Compare the operand lists.
10460 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10461 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10462 continue;
10463
10464 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10465 // if one of the PHIs has a constant for the index. The index may be
10466 // substantially cheaper to compute for the constants, so making it a
10467 // variable index could pessimize the path. This also handles the case
10468 // for struct indices, which must always be constant.
10469 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10470 isa<ConstantInt>(GEP->getOperand(op)))
10471 return 0;
10472
10473 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10474 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010475
10476 // If we already needed a PHI for an earlier operand, and another operand
10477 // also requires a PHI, we'd be introducing more PHIs than we're
10478 // eliminating, which increases register pressure on entry to the PHI's
10479 // block.
10480 if (NeededPhi)
10481 return 0;
10482
Chris Lattner05f18922008-12-01 02:34:36 +000010483 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010484 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010485 }
10486 }
10487
Chris Lattner36d3e322009-02-21 00:46:50 +000010488 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010489 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010490 // offset calculation, but all the predecessors will have to materialize the
10491 // stack address into a register anyway. We'd actually rather *clone* the
10492 // load up into the predecessors so that we have a load of a gep of an alloca,
10493 // which can usually all be folded into the load.
10494 if (AllBasePointersAreAllocas)
10495 return 0;
10496
Chris Lattner05f18922008-12-01 02:34:36 +000010497 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10498 // that is variable.
10499 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10500
10501 bool HasAnyPHIs = false;
10502 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10503 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10504 Value *FirstOp = FirstInst->getOperand(i);
10505 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10506 FirstOp->getName()+".pn");
10507 InsertNewInstBefore(NewPN, PN);
10508
10509 NewPN->reserveOperandSpace(e);
10510 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10511 OperandPhis[i] = NewPN;
10512 FixedOperands[i] = NewPN;
10513 HasAnyPHIs = true;
10514 }
10515
10516
10517 // Add all operands to the new PHIs.
10518 if (HasAnyPHIs) {
10519 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10520 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10521 BasicBlock *InBB = PN.getIncomingBlock(i);
10522
10523 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10524 if (PHINode *OpPhi = OperandPhis[op])
10525 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10526 }
10527 }
10528
10529 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010530 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10531 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10532 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010533 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10534 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010535}
10536
10537
Chris Lattner21550882009-02-23 05:56:17 +000010538/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10539/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010540/// obvious the value of the load is not changed from the point of the load to
10541/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010542///
10543/// Finally, it is safe, but not profitable, to sink a load targetting a
10544/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10545/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010546static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010547 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10548
10549 for (++BBI; BBI != E; ++BBI)
10550 if (BBI->mayWriteToMemory())
10551 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010552
10553 // Check for non-address taken alloca. If not address-taken already, it isn't
10554 // profitable to do this xform.
10555 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10556 bool isAddressTaken = false;
10557 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10558 UI != E; ++UI) {
10559 if (isa<LoadInst>(UI)) continue;
10560 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10561 // If storing TO the alloca, then the address isn't taken.
10562 if (SI->getOperand(1) == AI) continue;
10563 }
10564 isAddressTaken = true;
10565 break;
10566 }
10567
Chris Lattner36d3e322009-02-21 00:46:50 +000010568 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010569 return false;
10570 }
10571
Chris Lattner36d3e322009-02-21 00:46:50 +000010572 // If this load is a load from a GEP with a constant offset from an alloca,
10573 // then we don't want to sink it. In its present form, it will be
10574 // load [constant stack offset]. Sinking it will cause us to have to
10575 // materialize the stack addresses in each predecessor in a register only to
10576 // do a shared load from register in the successor.
10577 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10578 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10579 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10580 return false;
10581
Chris Lattner76c73142006-11-01 07:13:54 +000010582 return true;
10583}
10584
Chris Lattner9fe38862003-06-19 17:00:31 +000010585
Chris Lattnerbac32862004-11-14 19:13:23 +000010586// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10587// operator and they all are only used by the PHI, PHI together their
10588// inputs, and do the operation once, to the result of the PHI.
10589Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10590 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10591
10592 // Scan the instruction, looking for input operations that can be folded away.
10593 // If all input operands to the phi are the same instruction (e.g. a cast from
10594 // the same type or "+42") we can pull the operation through the PHI, reducing
10595 // code size and simplifying code.
10596 Constant *ConstantOp = 0;
10597 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010598 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010599 if (isa<CastInst>(FirstInst)) {
10600 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010601 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010602 // Can fold binop, compare or shift here if the RHS is a constant,
10603 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010604 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010605 if (ConstantOp == 0)
10606 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010607 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10608 isVolatile = LI->isVolatile();
10609 // We can't sink the load if the loaded value could be modified between the
10610 // load and the PHI.
10611 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010612 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010613 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010614
10615 // If the PHI is of volatile loads and the load block has multiple
10616 // successors, sinking it would remove a load of the volatile value from
10617 // the path through the other successor.
10618 if (isVolatile &&
10619 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10620 return 0;
10621
Chris Lattner9c080502006-11-01 07:43:41 +000010622 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010623 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010624 } else {
10625 return 0; // Cannot fold this operation.
10626 }
10627
10628 // Check to see if all arguments are the same operation.
10629 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10630 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10631 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010632 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010633 return 0;
10634 if (CastSrcTy) {
10635 if (I->getOperand(0)->getType() != CastSrcTy)
10636 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010637 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010638 // We can't sink the load if the loaded value could be modified between
10639 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010640 if (LI->isVolatile() != isVolatile ||
10641 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010642 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010643 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010644
Chris Lattner71042962008-07-08 17:18:32 +000010645 // If the PHI is of volatile loads and the load block has multiple
10646 // successors, sinking it would remove a load of the volatile value from
10647 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010648 if (isVolatile &&
10649 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10650 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010651
Chris Lattnerbac32862004-11-14 19:13:23 +000010652 } else if (I->getOperand(1) != ConstantOp) {
10653 return 0;
10654 }
10655 }
10656
10657 // Okay, they are all the same operation. Create a new PHI node of the
10658 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010659 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10660 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010661 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010662
10663 Value *InVal = FirstInst->getOperand(0);
10664 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010665
10666 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010667 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10668 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10669 if (NewInVal != InVal)
10670 InVal = 0;
10671 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10672 }
10673
10674 Value *PhiVal;
10675 if (InVal) {
10676 // The new PHI unions all of the same values together. This is really
10677 // common, so we handle it intelligently here for compile-time speed.
10678 PhiVal = InVal;
10679 delete NewPN;
10680 } else {
10681 InsertNewInstBefore(NewPN, PN);
10682 PhiVal = NewPN;
10683 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010684
Chris Lattnerbac32862004-11-14 19:13:23 +000010685 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010686 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010687 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010688 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010689 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010690 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010691 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010692 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010693 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10694
10695 // If this was a volatile load that we are merging, make sure to loop through
10696 // and mark all the input loads as non-volatile. If we don't do this, we will
10697 // insert a new volatile load and the old ones will not be deletable.
10698 if (isVolatile)
10699 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10700 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10701
10702 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010703}
Chris Lattnera1be5662002-05-02 17:06:02 +000010704
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010705/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10706/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010707static bool DeadPHICycle(PHINode *PN,
10708 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010709 if (PN->use_empty()) return true;
10710 if (!PN->hasOneUse()) return false;
10711
10712 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010713 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010714 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010715
10716 // Don't scan crazily complex things.
10717 if (PotentiallyDeadPHIs.size() == 16)
10718 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010719
10720 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10721 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010722
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010723 return false;
10724}
10725
Chris Lattnercf5008a2007-11-06 21:52:06 +000010726/// PHIsEqualValue - Return true if this phi node is always equal to
10727/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10728/// z = some value; x = phi (y, z); y = phi (x, z)
10729static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10730 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10731 // See if we already saw this PHI node.
10732 if (!ValueEqualPHIs.insert(PN))
10733 return true;
10734
10735 // Don't scan crazily complex things.
10736 if (ValueEqualPHIs.size() == 16)
10737 return false;
10738
10739 // Scan the operands to see if they are either phi nodes or are equal to
10740 // the value.
10741 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10742 Value *Op = PN->getIncomingValue(i);
10743 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10744 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10745 return false;
10746 } else if (Op != NonPhiInVal)
10747 return false;
10748 }
10749
10750 return true;
10751}
10752
10753
Chris Lattner473945d2002-05-06 18:06:38 +000010754// PHINode simplification
10755//
Chris Lattner7e708292002-06-25 16:13:24 +000010756Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010757 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010758 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010759
Owen Anderson7e057142006-07-10 22:03:18 +000010760 if (Value *V = PN.hasConstantValue())
10761 return ReplaceInstUsesWith(PN, V);
10762
Owen Anderson7e057142006-07-10 22:03:18 +000010763 // If all PHI operands are the same operation, pull them through the PHI,
10764 // reducing code size.
10765 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010766 isa<Instruction>(PN.getIncomingValue(1)) &&
10767 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10768 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10769 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10770 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010771 PN.getIncomingValue(0)->hasOneUse())
10772 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10773 return Result;
10774
10775 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10776 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10777 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010778 if (PN.hasOneUse()) {
10779 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10780 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010781 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010782 PotentiallyDeadPHIs.insert(&PN);
10783 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010784 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010785 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010786
10787 // If this phi has a single use, and if that use just computes a value for
10788 // the next iteration of a loop, delete the phi. This occurs with unused
10789 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10790 // common case here is good because the only other things that catch this
10791 // are induction variable analysis (sometimes) and ADCE, which is only run
10792 // late.
10793 if (PHIUser->hasOneUse() &&
10794 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10795 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010796 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010797 }
10798 }
Owen Anderson7e057142006-07-10 22:03:18 +000010799
Chris Lattnercf5008a2007-11-06 21:52:06 +000010800 // We sometimes end up with phi cycles that non-obviously end up being the
10801 // same value, for example:
10802 // z = some value; x = phi (y, z); y = phi (x, z)
10803 // where the phi nodes don't necessarily need to be in the same block. Do a
10804 // quick check to see if the PHI node only contains a single non-phi value, if
10805 // so, scan to see if the phi cycle is actually equal to that value.
10806 {
10807 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10808 // Scan for the first non-phi operand.
10809 while (InValNo != NumOperandVals &&
10810 isa<PHINode>(PN.getIncomingValue(InValNo)))
10811 ++InValNo;
10812
10813 if (InValNo != NumOperandVals) {
10814 Value *NonPhiInVal = PN.getOperand(InValNo);
10815
10816 // Scan the rest of the operands to see if there are any conflicts, if so
10817 // there is no need to recursively scan other phis.
10818 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10819 Value *OpVal = PN.getIncomingValue(InValNo);
10820 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10821 break;
10822 }
10823
10824 // If we scanned over all operands, then we have one unique value plus
10825 // phi values. Scan PHI nodes to see if they all merge in each other or
10826 // the value.
10827 if (InValNo == NumOperandVals) {
10828 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10829 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10830 return ReplaceInstUsesWith(PN, NonPhiInVal);
10831 }
10832 }
10833 }
Chris Lattner60921c92003-12-19 05:58:40 +000010834 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010835}
10836
Chris Lattner7e708292002-06-25 16:13:24 +000010837Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010838 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010839 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010840 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010841 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010842
Chris Lattnere87597f2004-10-16 18:11:37 +000010843 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010844 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010845
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010846 bool HasZeroPointerIndex = false;
10847 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10848 HasZeroPointerIndex = C->isNullValue();
10849
10850 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010851 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010852
Chris Lattner28977af2004-04-05 01:30:19 +000010853 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010854 if (TD) {
10855 bool MadeChange = false;
10856 unsigned PtrSize = TD->getPointerSizeInBits();
10857
10858 gep_type_iterator GTI = gep_type_begin(GEP);
10859 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10860 I != E; ++I, ++GTI) {
10861 if (!isa<SequentialType>(*GTI)) continue;
10862
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010863 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010864 // to what we need. If narrower, sign-extend it to what we need. This
10865 // explicit cast can make subsequent optimizations more obvious.
10866 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010867 if (OpBits == PtrSize)
10868 continue;
10869
Chris Lattner2345d1d2009-08-30 20:01:10 +000010870 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010871 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010872 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010873 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010874 }
Chris Lattner28977af2004-04-05 01:30:19 +000010875
Chris Lattner90ac28c2002-08-02 19:29:35 +000010876 // Combine Indices - If the source pointer to this getelementptr instruction
10877 // is a getelementptr instruction, combine the indices of the two
10878 // getelementptr instructions into a single instruction.
10879 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010880 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010881 // Note that if our source is a gep chain itself that we wait for that
10882 // chain to be resolved before we perform this transformation. This
10883 // avoids us creating a TON of code in some cases.
10884 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010885 if (GetElementPtrInst *SrcGEP =
10886 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10887 if (SrcGEP->getNumOperands() == 2)
10888 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010889
Chris Lattner72588fc2007-02-15 22:48:32 +000010890 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010891
10892 // Find out whether the last index in the source GEP is a sequential idx.
10893 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010894 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10895 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010896 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010897
Chris Lattner90ac28c2002-08-02 19:29:35 +000010898 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010899 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010900 // Replace: gep (gep %P, long B), long A, ...
10901 // With: T = long A+B; gep %P, T, ...
10902 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010903 Value *Sum;
10904 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10905 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010906 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010907 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010908 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010909 Sum = SO1;
10910 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010911 // If they aren't the same type, then the input hasn't been processed
10912 // by the loop above yet (which canonicalizes sequential index types to
10913 // intptr_t). Just avoid transforming this until the input has been
10914 // normalized.
10915 if (SO1->getType() != GO1->getType())
10916 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010917 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010918 }
Chris Lattner620ce142004-05-07 22:09:22 +000010919
Chris Lattnerab984842009-08-30 05:30:55 +000010920 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010921 if (Src->getNumOperands() == 2) {
10922 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010923 GEP.setOperand(1, Sum);
10924 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010925 }
Chris Lattnerab984842009-08-30 05:30:55 +000010926 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010927 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010928 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010929 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010930 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010931 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010932 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010933 Indices.append(Src->op_begin()+1, Src->op_end());
10934 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010935 }
10936
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010937 if (!Indices.empty())
10938 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10939 Src->isInBounds()) ?
10940 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10941 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010942 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010943 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010944 }
10945
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010946 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10947 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010948 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010949
Chris Lattner2de23192009-08-30 20:38:21 +000010950 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10951 // want to change the gep until the bitcasts are eliminated.
10952 if (getBitCastOperand(X)) {
10953 Worklist.AddValue(PtrOp);
10954 return 0;
10955 }
10956
Chris Lattner963f4ba2009-08-30 20:36:46 +000010957 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10958 // into : GEP [10 x i8]* X, i32 0, ...
10959 //
10960 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10961 // into : GEP i8* X, ...
10962 //
10963 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000010964 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000010965 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10966 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010967 if (const ArrayType *CATy =
10968 dyn_cast<ArrayType>(CPTy->getElementType())) {
10969 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10970 if (CATy->getElementType() == XTy->getElementType()) {
10971 // -> GEP i8* X, ...
10972 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010973 return cast<GEPOperator>(&GEP)->isInBounds() ?
10974 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
10975 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010976 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10977 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000010978 }
10979
10980 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010981 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010982 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010983 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010984 // At this point, we know that the cast source type is a pointer
10985 // to an array of the same type as the destination pointer
10986 // array. Because the array type is never stepped over (there
10987 // is a leading zero) we can fold the cast into this GEP.
10988 GEP.setOperand(0, X);
10989 return &GEP;
10990 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010991 }
10992 }
Chris Lattnereed48272005-09-13 00:40:14 +000010993 } else if (GEP.getNumOperands() == 2) {
10994 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010995 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10996 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010997 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10998 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010999 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011000 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11001 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011002 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011003 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011004 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011005 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11006 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011007 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011008 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011009 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011010 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011011
11012 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011013 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011014 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011015 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011016
Owen Anderson1d0be152009-08-13 21:58:54 +000011017 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011018 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011019 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011020
11021 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11022 // allow either a mul, shift, or constant here.
11023 Value *NewIdx = 0;
11024 ConstantInt *Scale = 0;
11025 if (ArrayEltSize == 1) {
11026 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011027 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011028 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011029 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011030 Scale = CI;
11031 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11032 if (Inst->getOpcode() == Instruction::Shl &&
11033 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011034 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11035 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011036 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011037 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011038 NewIdx = Inst->getOperand(0);
11039 } else if (Inst->getOpcode() == Instruction::Mul &&
11040 isa<ConstantInt>(Inst->getOperand(1))) {
11041 Scale = cast<ConstantInt>(Inst->getOperand(1));
11042 NewIdx = Inst->getOperand(0);
11043 }
11044 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011045
Chris Lattner7835cdd2005-09-13 18:36:04 +000011046 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011047 // out, perform the transformation. Note, we don't know whether Scale is
11048 // signed or not. We'll use unsigned version of division/modulo
11049 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011050 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011051 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011052 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011053 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011054 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011055 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11056 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011057 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011058 }
11059
11060 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011061 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011062 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011063 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011064 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11065 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11066 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011067 // The NewGEP must be pointer typed, so must the old one -> BitCast
11068 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011069 }
11070 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011071 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011072 }
Chris Lattner58407792009-01-09 04:53:57 +000011073
Chris Lattner46cd5a12009-01-09 05:44:56 +000011074 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011075 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011076 /// Y = gep X, <...constant indices...>
11077 /// into a gep of the original struct. This is important for SROA and alias
11078 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011079 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011080 if (TD &&
11081 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011082 // Determine how much the GEP moves the pointer. We are guaranteed to get
11083 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011084 ConstantInt *OffsetV =
11085 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011086 int64_t Offset = OffsetV->getSExtValue();
11087
11088 // If this GEP instruction doesn't move the pointer, just replace the GEP
11089 // with a bitcast of the real input to the dest type.
11090 if (Offset == 0) {
11091 // If the bitcast is of an allocation, and the allocation will be
11092 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011093 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11094 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011095 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11096 if (Instruction *I = visitBitCast(*BCI)) {
11097 if (I != BCI) {
11098 I->takeName(BCI);
11099 BCI->getParent()->getInstList().insert(BCI, I);
11100 ReplaceInstUsesWith(*BCI, I);
11101 }
11102 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011103 }
Chris Lattner58407792009-01-09 04:53:57 +000011104 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011105 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011106 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011107
11108 // Otherwise, if the offset is non-zero, we need to find out if there is a
11109 // field at Offset in 'A's type. If so, we can pull the cast through the
11110 // GEP.
11111 SmallVector<Value*, 8> NewIndices;
11112 const Type *InTy =
11113 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011114 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011115 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11116 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11117 NewIndices.end()) :
11118 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11119 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011120
11121 if (NGEP->getType() == GEP.getType())
11122 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011123 NGEP->takeName(&GEP);
11124 return new BitCastInst(NGEP, GEP.getType());
11125 }
Chris Lattner58407792009-01-09 04:53:57 +000011126 }
11127 }
11128
Chris Lattner8a2a3112001-12-14 16:52:21 +000011129 return 0;
11130}
11131
Chris Lattner0864acf2002-11-04 16:18:53 +000011132Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11133 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011134 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011135 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11136 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011137 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011138 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011139
11140 // Create and insert the replacement instruction...
11141 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011142 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011143 else {
11144 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011145 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011146 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011147 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011148
Chris Lattner0864acf2002-11-04 16:18:53 +000011149 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011150 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011151 //
11152 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011153 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011154
11155 // Now that I is pointing to the first non-allocation-inst in the block,
11156 // insert our getelementptr instruction...
11157 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011158 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011159 Value *Idx[2];
11160 Idx[0] = NullIdx;
11161 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011162 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11163 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011164
11165 // Now make everything use the getelementptr instead of the original
11166 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011167 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011168 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011169 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011170 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011171 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011172
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011173 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011174 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011175 // Note that we only do this for alloca's, because malloc should allocate
11176 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011177 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011178 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011179
11180 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11181 if (AI.getAlignment() == 0)
11182 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11183 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011184
Chris Lattner0864acf2002-11-04 16:18:53 +000011185 return 0;
11186}
11187
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011188Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11189 Value *Op = FI.getOperand(0);
11190
Chris Lattner17be6352004-10-18 02:59:09 +000011191 // free undef -> unreachable.
11192 if (isa<UndefValue>(Op)) {
11193 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011194 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011195 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011196 return EraseInstFromFunction(FI);
11197 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011198
Chris Lattner6160e852004-02-28 04:57:37 +000011199 // If we have 'free null' delete the instruction. This can happen in stl code
11200 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011201 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011202 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011203
11204 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11205 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11206 FI.setOperand(0, CI->getOperand(0));
11207 return &FI;
11208 }
11209
11210 // Change free (gep X, 0,0,0,0) into free(X)
11211 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11212 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011213 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011214 FI.setOperand(0, GEPI->getOperand(0));
11215 return &FI;
11216 }
11217 }
11218
11219 // Change free(malloc) into nothing, if the malloc has a single use.
11220 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11221 if (MI->hasOneUse()) {
11222 EraseInstFromFunction(FI);
11223 return EraseInstFromFunction(*MI);
11224 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011225 if (isMalloc(Op)) {
11226 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11227 if (Op->hasOneUse() && CI->hasOneUse()) {
11228 EraseInstFromFunction(FI);
11229 EraseInstFromFunction(*CI);
11230 return EraseInstFromFunction(*cast<Instruction>(Op));
11231 }
11232 } else {
11233 // Op is a call to malloc
11234 if (Op->hasOneUse()) {
11235 EraseInstFromFunction(FI);
11236 return EraseInstFromFunction(*cast<Instruction>(Op));
11237 }
11238 }
11239 }
Chris Lattner6160e852004-02-28 04:57:37 +000011240
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011241 return 0;
11242}
11243
11244
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011245/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011246static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011247 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011248 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011249 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011250 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011251
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011252 if (TD) {
11253 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11254 // Instead of loading constant c string, use corresponding integer value
11255 // directly if string length is small enough.
11256 std::string Str;
11257 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11258 unsigned len = Str.length();
11259 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11260 unsigned numBits = Ty->getPrimitiveSizeInBits();
11261 // Replace LI with immediate integer store.
11262 if ((numBits >> 3) == len + 1) {
11263 APInt StrVal(numBits, 0);
11264 APInt SingleChar(numBits, 0);
11265 if (TD->isLittleEndian()) {
11266 for (signed i = len-1; i >= 0; i--) {
11267 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11268 StrVal = (StrVal << 8) | SingleChar;
11269 }
11270 } else {
11271 for (unsigned i = 0; i < len; i++) {
11272 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11273 StrVal = (StrVal << 8) | SingleChar;
11274 }
11275 // Append NULL at the end.
11276 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011277 StrVal = (StrVal << 8) | SingleChar;
11278 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011279 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011280 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011281 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011282 }
11283 }
11284 }
11285
Mon P Wang6753f952009-02-07 22:19:29 +000011286 const PointerType *DestTy = cast<PointerType>(CI->getType());
11287 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011288 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011289
11290 // If the address spaces don't match, don't eliminate the cast.
11291 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11292 return 0;
11293
Chris Lattnerb89e0712004-07-13 01:49:43 +000011294 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011295
Reid Spencer42230162007-01-22 05:51:25 +000011296 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011297 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011298 // If the source is an array, the code below will not succeed. Check to
11299 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11300 // constants.
11301 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11302 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11303 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011304 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011305 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011306 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011307 SrcTy = cast<PointerType>(CastOp->getType());
11308 SrcPTy = SrcTy->getElementType();
11309 }
11310
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011311 if (IC.getTargetData() &&
11312 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011313 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011314 // Do not allow turning this into a load of an integer, which is then
11315 // casted to a pointer, this pessimizes pointer analysis a lot.
11316 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011317 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11318 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011319
Chris Lattnerf9527852005-01-31 04:50:46 +000011320 // Okay, we are casting from one integer or pointer type to another of
11321 // the same size. Instead of casting the pointer before the load, cast
11322 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011323 Value *NewLoad =
11324 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011325 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011326 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011327 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011328 }
11329 }
11330 return 0;
11331}
11332
Chris Lattner833b8a42003-06-26 05:06:25 +000011333Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11334 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011335
Dan Gohman9941f742007-07-20 16:34:21 +000011336 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011337 if (TD) {
11338 unsigned KnownAlign =
11339 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11340 if (KnownAlign >
11341 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11342 LI.getAlignment()))
11343 LI.setAlignment(KnownAlign);
11344 }
Dan Gohman9941f742007-07-20 16:34:21 +000011345
Chris Lattner963f4ba2009-08-30 20:36:46 +000011346 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011347 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011348 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011349 return Res;
11350
11351 // None of the following transforms are legal for volatile loads.
11352 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011353
Dan Gohman2276a7b2008-10-15 23:19:35 +000011354 // Do really simple store-to-load forwarding and load CSE, to catch cases
11355 // where there are several consequtive memory accesses to the same location,
11356 // separated by a few arithmetic operations.
11357 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011358 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11359 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011360
Christopher Lambb15147e2007-12-29 07:56:53 +000011361 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11362 const Value *GEPI0 = GEPI->getOperand(0);
11363 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011364 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011365 // Insert a new store to null instruction before the load to indicate
11366 // that this code is not reachable. We do this instead of inserting
11367 // an unreachable instruction directly because we cannot modify the
11368 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011369 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011370 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011371 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011372 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011373 }
Chris Lattner37366c12005-05-01 04:24:53 +000011374
Chris Lattnere87597f2004-10-16 18:11:37 +000011375 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011376 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011377 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011378 if (isa<UndefValue>(C) ||
11379 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011380 // Insert a new store to null instruction before the load to indicate that
11381 // this code is not reachable. We do this instead of inserting an
11382 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011383 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011384 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011385 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011386 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011387
Chris Lattnere87597f2004-10-16 18:11:37 +000011388 // Instcombine load (constant global) into the value loaded.
11389 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011390 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011391 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011392
Chris Lattnere87597f2004-10-16 18:11:37 +000011393 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011394 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011395 if (CE->getOpcode() == Instruction::GetElementPtr) {
11396 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011397 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011398 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011399 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011400 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011401 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011402 if (CE->getOperand(0)->isNullValue()) {
11403 // Insert a new store to null instruction before the load to indicate
11404 // that this code is not reachable. We do this instead of inserting
11405 // an unreachable instruction directly because we cannot modify the
11406 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011407 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011408 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011409 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011410 }
11411
Reid Spencer3da59db2006-11-27 01:05:10 +000011412 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011413 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011414 return Res;
11415 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011416 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011417 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011418
11419 // If this load comes from anywhere in a constant global, and if the global
11420 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011421 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011422 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011423 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011424 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011425 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011426 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011427 }
11428 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011429
Chris Lattner37366c12005-05-01 04:24:53 +000011430 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011431 // Change select and PHI nodes to select values instead of addresses: this
11432 // helps alias analysis out a lot, allows many others simplifications, and
11433 // exposes redundancy in the code.
11434 //
11435 // Note that we cannot do the transformation unless we know that the
11436 // introduced loads cannot trap! Something like this is valid as long as
11437 // the condition is always false: load (select bool %C, int* null, int* %G),
11438 // but it would not be valid if we transformed it to load from null
11439 // unconditionally.
11440 //
11441 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11442 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011443 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11444 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011445 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11446 SI->getOperand(1)->getName()+".val");
11447 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11448 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011449 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011450 }
11451
Chris Lattner684fe212004-09-23 15:46:00 +000011452 // load (select (cond, null, P)) -> load P
11453 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11454 if (C->isNullValue()) {
11455 LI.setOperand(0, SI->getOperand(2));
11456 return &LI;
11457 }
11458
11459 // load (select (cond, P, null)) -> load P
11460 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11461 if (C->isNullValue()) {
11462 LI.setOperand(0, SI->getOperand(1));
11463 return &LI;
11464 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011465 }
11466 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011467 return 0;
11468}
11469
Reid Spencer55af2b52007-01-19 21:20:31 +000011470/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011471/// when possible. This makes it generally easy to do alias analysis and/or
11472/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011473static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11474 User *CI = cast<User>(SI.getOperand(1));
11475 Value *CastOp = CI->getOperand(0);
11476
11477 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011478 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11479 if (SrcTy == 0) return 0;
11480
11481 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011482
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011483 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11484 return 0;
11485
Chris Lattner3914f722009-01-24 01:00:13 +000011486 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11487 /// to its first element. This allows us to handle things like:
11488 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11489 /// on 32-bit hosts.
11490 SmallVector<Value*, 4> NewGEPIndices;
11491
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011492 // If the source is an array, the code below will not succeed. Check to
11493 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11494 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011495 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11496 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011497 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011498 NewGEPIndices.push_back(Zero);
11499
11500 while (1) {
11501 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011502 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011503 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011504 NewGEPIndices.push_back(Zero);
11505 SrcPTy = STy->getElementType(0);
11506 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11507 NewGEPIndices.push_back(Zero);
11508 SrcPTy = ATy->getElementType();
11509 } else {
11510 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011511 }
Chris Lattner3914f722009-01-24 01:00:13 +000011512 }
11513
Owen Andersondebcb012009-07-29 22:17:13 +000011514 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011515 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011516
11517 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11518 return 0;
11519
Chris Lattner71759c42009-01-16 20:12:52 +000011520 // If the pointers point into different address spaces or if they point to
11521 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011522 if (!IC.getTargetData() ||
11523 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011524 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011525 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11526 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011527 return 0;
11528
11529 // Okay, we are casting from one integer or pointer type to another of
11530 // the same size. Instead of casting the pointer before
11531 // the store, cast the value to be stored.
11532 Value *NewCast;
11533 Value *SIOp0 = SI.getOperand(0);
11534 Instruction::CastOps opcode = Instruction::BitCast;
11535 const Type* CastSrcTy = SIOp0->getType();
11536 const Type* CastDstTy = SrcPTy;
11537 if (isa<PointerType>(CastDstTy)) {
11538 if (CastSrcTy->isInteger())
11539 opcode = Instruction::IntToPtr;
11540 } else if (isa<IntegerType>(CastDstTy)) {
11541 if (isa<PointerType>(SIOp0->getType()))
11542 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011543 }
Chris Lattner3914f722009-01-24 01:00:13 +000011544
11545 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11546 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011547 if (!NewGEPIndices.empty())
11548 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11549 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011550
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011551 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11552 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011553 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011554}
11555
Chris Lattner4aebaee2008-11-27 08:56:30 +000011556/// equivalentAddressValues - Test if A and B will obviously have the same
11557/// value. This includes recognizing that %t0 and %t1 will have the same
11558/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011559/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011560/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011561/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011562/// %t2 = load i32* %t1
11563///
11564static bool equivalentAddressValues(Value *A, Value *B) {
11565 // Test if the values are trivially equivalent.
11566 if (A == B) return true;
11567
11568 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011569 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11570 // its only used to compare two uses within the same basic block, which
11571 // means that they'll always either have the same value or one of them
11572 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011573 if (isa<BinaryOperator>(A) ||
11574 isa<CastInst>(A) ||
11575 isa<PHINode>(A) ||
11576 isa<GetElementPtrInst>(A))
11577 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011578 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011579 return true;
11580
11581 // Otherwise they may not be equivalent.
11582 return false;
11583}
11584
Dale Johannesen4945c652009-03-03 21:26:39 +000011585// If this instruction has two uses, one of which is a llvm.dbg.declare,
11586// return the llvm.dbg.declare.
11587DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11588 if (!V->hasNUses(2))
11589 return 0;
11590 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11591 UI != E; ++UI) {
11592 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11593 return DI;
11594 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11595 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11596 return DI;
11597 }
11598 }
11599 return 0;
11600}
11601
Chris Lattner2f503e62005-01-31 05:36:43 +000011602Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11603 Value *Val = SI.getOperand(0);
11604 Value *Ptr = SI.getOperand(1);
11605
11606 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011607 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011608 ++NumCombined;
11609 return 0;
11610 }
Chris Lattner836692d2007-01-15 06:51:56 +000011611
11612 // If the RHS is an alloca with a single use, zapify the store, making the
11613 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011614 // If the RHS is an alloca with a two uses, the other one being a
11615 // llvm.dbg.declare, zapify the store and the declare, making the
11616 // alloca dead. We must do this to prevent declare's from affecting
11617 // codegen.
11618 if (!SI.isVolatile()) {
11619 if (Ptr->hasOneUse()) {
11620 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011621 EraseInstFromFunction(SI);
11622 ++NumCombined;
11623 return 0;
11624 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011625 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11626 if (isa<AllocaInst>(GEP->getOperand(0))) {
11627 if (GEP->getOperand(0)->hasOneUse()) {
11628 EraseInstFromFunction(SI);
11629 ++NumCombined;
11630 return 0;
11631 }
11632 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11633 EraseInstFromFunction(*DI);
11634 EraseInstFromFunction(SI);
11635 ++NumCombined;
11636 return 0;
11637 }
11638 }
11639 }
11640 }
11641 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11642 EraseInstFromFunction(*DI);
11643 EraseInstFromFunction(SI);
11644 ++NumCombined;
11645 return 0;
11646 }
Chris Lattner836692d2007-01-15 06:51:56 +000011647 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011648
Dan Gohman9941f742007-07-20 16:34:21 +000011649 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011650 if (TD) {
11651 unsigned KnownAlign =
11652 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11653 if (KnownAlign >
11654 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11655 SI.getAlignment()))
11656 SI.setAlignment(KnownAlign);
11657 }
Dan Gohman9941f742007-07-20 16:34:21 +000011658
Dale Johannesenacb51a32009-03-03 01:43:03 +000011659 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011660 // stores to the same location, separated by a few arithmetic operations. This
11661 // situation often occurs with bitfield accesses.
11662 BasicBlock::iterator BBI = &SI;
11663 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11664 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011665 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011666 // Don't count debug info directives, lest they affect codegen,
11667 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11668 // It is necessary for correctness to skip those that feed into a
11669 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011670 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011671 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011672 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011673 continue;
11674 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011675
11676 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11677 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011678 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11679 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011680 ++NumDeadStore;
11681 ++BBI;
11682 EraseInstFromFunction(*PrevSI);
11683 continue;
11684 }
11685 break;
11686 }
11687
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011688 // If this is a load, we have to stop. However, if the loaded value is from
11689 // the pointer we're loading and is producing the pointer we're storing,
11690 // then *this* store is dead (X = load P; store X -> P).
11691 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011692 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11693 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011694 EraseInstFromFunction(SI);
11695 ++NumCombined;
11696 return 0;
11697 }
11698 // Otherwise, this is a load from some other location. Stores before it
11699 // may not be dead.
11700 break;
11701 }
11702
Chris Lattner9ca96412006-02-08 03:25:32 +000011703 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011704 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011705 break;
11706 }
11707
11708
11709 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011710
11711 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011712 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011713 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011714 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011715 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011716 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011717 ++NumCombined;
11718 }
11719 return 0; // Do not modify these!
11720 }
11721
11722 // store undef, Ptr -> noop
11723 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011724 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011725 ++NumCombined;
11726 return 0;
11727 }
11728
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011729 // If the pointer destination is a cast, see if we can fold the cast into the
11730 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011731 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011732 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11733 return Res;
11734 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011735 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011736 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11737 return Res;
11738
Chris Lattner408902b2005-09-12 23:23:25 +000011739
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011740 // If this store is the last instruction in the basic block (possibly
11741 // excepting debug info instructions and the pointer bitcasts that feed
11742 // into them), and if the block ends with an unconditional branch, try
11743 // to move it to the successor block.
11744 BBI = &SI;
11745 do {
11746 ++BBI;
11747 } while (isa<DbgInfoIntrinsic>(BBI) ||
11748 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011749 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011750 if (BI->isUnconditional())
11751 if (SimplifyStoreAtEndOfBlock(SI))
11752 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011753
Chris Lattner2f503e62005-01-31 05:36:43 +000011754 return 0;
11755}
11756
Chris Lattner3284d1f2007-04-15 00:07:55 +000011757/// SimplifyStoreAtEndOfBlock - Turn things like:
11758/// if () { *P = v1; } else { *P = v2 }
11759/// into a phi node with a store in the successor.
11760///
Chris Lattner31755a02007-04-15 01:02:18 +000011761/// Simplify things like:
11762/// *P = v1; if () { *P = v2; }
11763/// into a phi node with a store in the successor.
11764///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011765bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11766 BasicBlock *StoreBB = SI.getParent();
11767
11768 // Check to see if the successor block has exactly two incoming edges. If
11769 // so, see if the other predecessor contains a store to the same location.
11770 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011771 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011772
11773 // Determine whether Dest has exactly two predecessors and, if so, compute
11774 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011775 pred_iterator PI = pred_begin(DestBB);
11776 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011777 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011778 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011779 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011780 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011781 return false;
11782
11783 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011784 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011785 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011786 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011787 }
Chris Lattner31755a02007-04-15 01:02:18 +000011788 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011789 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011790
11791 // Bail out if all the relevant blocks aren't distinct (this can happen,
11792 // for example, if SI is in an infinite loop)
11793 if (StoreBB == DestBB || OtherBB == DestBB)
11794 return false;
11795
Chris Lattner31755a02007-04-15 01:02:18 +000011796 // Verify that the other block ends in a branch and is not otherwise empty.
11797 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011798 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011799 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011800 return false;
11801
Chris Lattner31755a02007-04-15 01:02:18 +000011802 // If the other block ends in an unconditional branch, check for the 'if then
11803 // else' case. there is an instruction before the branch.
11804 StoreInst *OtherStore = 0;
11805 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011806 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011807 // Skip over debugging info.
11808 while (isa<DbgInfoIntrinsic>(BBI) ||
11809 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11810 if (BBI==OtherBB->begin())
11811 return false;
11812 --BBI;
11813 }
11814 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011815 OtherStore = dyn_cast<StoreInst>(BBI);
11816 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11817 return false;
11818 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011819 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011820 // destinations is StoreBB, then we have the if/then case.
11821 if (OtherBr->getSuccessor(0) != StoreBB &&
11822 OtherBr->getSuccessor(1) != StoreBB)
11823 return false;
11824
11825 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011826 // if/then triangle. See if there is a store to the same ptr as SI that
11827 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011828 for (;; --BBI) {
11829 // Check to see if we find the matching store.
11830 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11831 if (OtherStore->getOperand(1) != SI.getOperand(1))
11832 return false;
11833 break;
11834 }
Eli Friedman6903a242008-06-13 22:02:12 +000011835 // If we find something that may be using or overwriting the stored
11836 // value, or if we run out of instructions, we can't do the xform.
11837 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011838 BBI == OtherBB->begin())
11839 return false;
11840 }
11841
11842 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011843 // make sure nothing reads or overwrites the stored value in
11844 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011845 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11846 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011847 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011848 return false;
11849 }
11850 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011851
Chris Lattner31755a02007-04-15 01:02:18 +000011852 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011853 Value *MergedVal = OtherStore->getOperand(0);
11854 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011855 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011856 PN->reserveOperandSpace(2);
11857 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011858 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11859 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011860 }
11861
11862 // Advance to a place where it is safe to insert the new store and
11863 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011864 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011865 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11866 OtherStore->isVolatile()), *BBI);
11867
11868 // Nuke the old stores.
11869 EraseInstFromFunction(SI);
11870 EraseInstFromFunction(*OtherStore);
11871 ++NumCombined;
11872 return true;
11873}
11874
Chris Lattner2f503e62005-01-31 05:36:43 +000011875
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011876Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11877 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011878 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011879 BasicBlock *TrueDest;
11880 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011881 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011882 !isa<Constant>(X)) {
11883 // Swap Destinations and condition...
11884 BI.setCondition(X);
11885 BI.setSuccessor(0, FalseDest);
11886 BI.setSuccessor(1, TrueDest);
11887 return &BI;
11888 }
11889
Reid Spencere4d87aa2006-12-23 06:05:41 +000011890 // Cannonicalize fcmp_one -> fcmp_oeq
11891 FCmpInst::Predicate FPred; Value *Y;
11892 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011893 TrueDest, FalseDest)) &&
11894 BI.getCondition()->hasOneUse())
11895 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11896 FPred == FCmpInst::FCMP_OGE) {
11897 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11898 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11899
11900 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011901 BI.setSuccessor(0, FalseDest);
11902 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011903 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011904 return &BI;
11905 }
11906
11907 // Cannonicalize icmp_ne -> icmp_eq
11908 ICmpInst::Predicate IPred;
11909 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011910 TrueDest, FalseDest)) &&
11911 BI.getCondition()->hasOneUse())
11912 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11913 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11914 IPred == ICmpInst::ICMP_SGE) {
11915 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11916 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11917 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011918 BI.setSuccessor(0, FalseDest);
11919 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011920 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011921 return &BI;
11922 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011923
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011924 return 0;
11925}
Chris Lattner0864acf2002-11-04 16:18:53 +000011926
Chris Lattner46238a62004-07-03 00:26:11 +000011927Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11928 Value *Cond = SI.getCondition();
11929 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11930 if (I->getOpcode() == Instruction::Add)
11931 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11932 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11933 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011934 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011935 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011936 AddRHS));
11937 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011938 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011939 return &SI;
11940 }
11941 }
11942 return 0;
11943}
11944
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011945Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011946 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011947
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011948 if (!EV.hasIndices())
11949 return ReplaceInstUsesWith(EV, Agg);
11950
11951 if (Constant *C = dyn_cast<Constant>(Agg)) {
11952 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011953 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011954
11955 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011956 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011957
11958 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11959 // Extract the element indexed by the first index out of the constant
11960 Value *V = C->getOperand(*EV.idx_begin());
11961 if (EV.getNumIndices() > 1)
11962 // Extract the remaining indices out of the constant indexed by the
11963 // first index
11964 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11965 else
11966 return ReplaceInstUsesWith(EV, V);
11967 }
11968 return 0; // Can't handle other constants
11969 }
11970 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11971 // We're extracting from an insertvalue instruction, compare the indices
11972 const unsigned *exti, *exte, *insi, *inse;
11973 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11974 exte = EV.idx_end(), inse = IV->idx_end();
11975 exti != exte && insi != inse;
11976 ++exti, ++insi) {
11977 if (*insi != *exti)
11978 // The insert and extract both reference distinctly different elements.
11979 // This means the extract is not influenced by the insert, and we can
11980 // replace the aggregate operand of the extract with the aggregate
11981 // operand of the insert. i.e., replace
11982 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11983 // %E = extractvalue { i32, { i32 } } %I, 0
11984 // with
11985 // %E = extractvalue { i32, { i32 } } %A, 0
11986 return ExtractValueInst::Create(IV->getAggregateOperand(),
11987 EV.idx_begin(), EV.idx_end());
11988 }
11989 if (exti == exte && insi == inse)
11990 // Both iterators are at the end: Index lists are identical. Replace
11991 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11992 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11993 // with "i32 42"
11994 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11995 if (exti == exte) {
11996 // The extract list is a prefix of the insert list. i.e. replace
11997 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11998 // %E = extractvalue { i32, { i32 } } %I, 1
11999 // with
12000 // %X = extractvalue { i32, { i32 } } %A, 1
12001 // %E = insertvalue { i32 } %X, i32 42, 0
12002 // by switching the order of the insert and extract (though the
12003 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012004 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12005 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012006 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12007 insi, inse);
12008 }
12009 if (insi == inse)
12010 // The insert list is a prefix of the extract list
12011 // We can simply remove the common indices from the extract and make it
12012 // operate on the inserted value instead of the insertvalue result.
12013 // i.e., replace
12014 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12015 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12016 // with
12017 // %E extractvalue { i32 } { i32 42 }, 0
12018 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12019 exti, exte);
12020 }
12021 // Can't simplify extracts from other values. Note that nested extracts are
12022 // already simplified implicitely by the above (extract ( extract (insert) )
12023 // will be translated into extract ( insert ( extract ) ) first and then just
12024 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012025 return 0;
12026}
12027
Chris Lattner220b0cf2006-03-05 00:22:33 +000012028/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12029/// is to leave as a vector operation.
12030static bool CheapToScalarize(Value *V, bool isConstant) {
12031 if (isa<ConstantAggregateZero>(V))
12032 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012033 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012034 if (isConstant) return true;
12035 // If all elts are the same, we can extract.
12036 Constant *Op0 = C->getOperand(0);
12037 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12038 if (C->getOperand(i) != Op0)
12039 return false;
12040 return true;
12041 }
12042 Instruction *I = dyn_cast<Instruction>(V);
12043 if (!I) return false;
12044
12045 // Insert element gets simplified to the inserted element or is deleted if
12046 // this is constant idx extract element and its a constant idx insertelt.
12047 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12048 isa<ConstantInt>(I->getOperand(2)))
12049 return true;
12050 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12051 return true;
12052 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12053 if (BO->hasOneUse() &&
12054 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12055 CheapToScalarize(BO->getOperand(1), isConstant)))
12056 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012057 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12058 if (CI->hasOneUse() &&
12059 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12060 CheapToScalarize(CI->getOperand(1), isConstant)))
12061 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012062
12063 return false;
12064}
12065
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012066/// Read and decode a shufflevector mask.
12067///
12068/// It turns undef elements into values that are larger than the number of
12069/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012070static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12071 unsigned NElts = SVI->getType()->getNumElements();
12072 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12073 return std::vector<unsigned>(NElts, 0);
12074 if (isa<UndefValue>(SVI->getOperand(2)))
12075 return std::vector<unsigned>(NElts, 2*NElts);
12076
12077 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012078 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012079 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12080 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012081 Result.push_back(NElts*2); // undef -> 8
12082 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012083 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012084 return Result;
12085}
12086
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012087/// FindScalarElement - Given a vector and an element number, see if the scalar
12088/// value is already around as a register, for example if it were inserted then
12089/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012090static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012091 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012092 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12093 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012094 unsigned Width = PTy->getNumElements();
12095 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012096 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012097
12098 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012099 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012100 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012101 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012102 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012103 return CP->getOperand(EltNo);
12104 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12105 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012106 if (!isa<ConstantInt>(III->getOperand(2)))
12107 return 0;
12108 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012109
12110 // If this is an insert to the element we are looking for, return the
12111 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012112 if (EltNo == IIElt)
12113 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012114
12115 // Otherwise, the insertelement doesn't modify the value, recurse on its
12116 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012117 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012118 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012119 unsigned LHSWidth =
12120 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012121 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012122 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012123 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012124 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012125 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012126 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012127 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012128 }
12129
12130 // Otherwise, we don't know.
12131 return 0;
12132}
12133
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012134Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012135 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012136 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012137 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012138
Dan Gohman07a96762007-07-16 14:29:03 +000012139 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012140 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012141 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012142
Reid Spencer9d6565a2007-02-15 02:26:10 +000012143 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012144 // If vector val is constant with all elements the same, replace EI with
12145 // that element. When the elements are not identical, we cannot replace yet
12146 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012147 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012148 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012149 if (C->getOperand(i) != op0) {
12150 op0 = 0;
12151 break;
12152 }
12153 if (op0)
12154 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012155 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012156
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012157 // If extracting a specified index from the vector, see if we can recursively
12158 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012159 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012160 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012161 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012162
12163 // If this is extracting an invalid index, turn this into undef, to avoid
12164 // crashing the code below.
12165 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012166 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012167
Chris Lattner867b99f2006-10-05 06:55:50 +000012168 // This instruction only demands the single element from the input vector.
12169 // If the input vector has a single use, simplify it based on this use
12170 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012171 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012172 APInt UndefElts(VectorWidth, 0);
12173 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012174 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012175 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012176 EI.setOperand(0, V);
12177 return &EI;
12178 }
12179 }
12180
Owen Andersond672ecb2009-07-03 00:17:18 +000012181 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012182 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012183
12184 // If the this extractelement is directly using a bitcast from a vector of
12185 // the same number of elements, see if we can find the source element from
12186 // it. In this case, we will end up needing to bitcast the scalars.
12187 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12188 if (const VectorType *VT =
12189 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12190 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012191 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12192 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012193 return new BitCastInst(Elt, EI.getType());
12194 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012195 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012196
Chris Lattner73fa49d2006-05-25 22:53:38 +000012197 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012198 // Push extractelement into predecessor operation if legal and
12199 // profitable to do so
12200 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12201 if (I->hasOneUse() &&
12202 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12203 Value *newEI0 =
12204 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12205 EI.getName()+".lhs");
12206 Value *newEI1 =
12207 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12208 EI.getName()+".rhs");
12209 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012210 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012211 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012212 // Extracting the inserted element?
12213 if (IE->getOperand(2) == EI.getOperand(1))
12214 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12215 // If the inserted and extracted elements are constants, they must not
12216 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012217 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012218 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012219 EI.setOperand(0, IE->getOperand(0));
12220 return &EI;
12221 }
12222 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12223 // If this is extracting an element from a shufflevector, figure out where
12224 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012225 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12226 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012227 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012228 unsigned LHSWidth =
12229 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12230
12231 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012232 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012233 else if (SrcIdx < LHSWidth*2) {
12234 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012235 Src = SVI->getOperand(1);
12236 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012237 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012238 }
Eric Christophera3500da2009-07-25 02:28:41 +000012239 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012240 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12241 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012242 }
12243 }
Eli Friedman2451a642009-07-18 23:06:53 +000012244 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012245 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012246 return 0;
12247}
12248
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012249/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12250/// elements from either LHS or RHS, return the shuffle mask and true.
12251/// Otherwise, return false.
12252static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012253 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012254 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012255 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12256 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012257 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012258
12259 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012260 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012261 return true;
12262 } else if (V == LHS) {
12263 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012264 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012265 return true;
12266 } else if (V == RHS) {
12267 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012268 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012269 return true;
12270 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12271 // If this is an insert of an extract from some other vector, include it.
12272 Value *VecOp = IEI->getOperand(0);
12273 Value *ScalarOp = IEI->getOperand(1);
12274 Value *IdxOp = IEI->getOperand(2);
12275
Chris Lattnerd929f062006-04-27 21:14:21 +000012276 if (!isa<ConstantInt>(IdxOp))
12277 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012278 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012279
12280 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12281 // Okay, we can handle this if the vector we are insertinting into is
12282 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012283 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012284 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012285 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012286 return true;
12287 }
12288 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12289 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012290 EI->getOperand(0)->getType() == V->getType()) {
12291 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012292 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012293
12294 // This must be extracting from either LHS or RHS.
12295 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12296 // Okay, we can handle this if the vector we are insertinting into is
12297 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012298 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012299 // If so, update the mask to reflect the inserted value.
12300 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012301 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012302 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012303 } else {
12304 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012305 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012306 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012307
12308 }
12309 return true;
12310 }
12311 }
12312 }
12313 }
12314 }
12315 // TODO: Handle shufflevector here!
12316
12317 return false;
12318}
12319
12320/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12321/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12322/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012323static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012324 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012325 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012326 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012327 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012328 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012329
12330 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012331 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012332 return V;
12333 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012334 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012335 return V;
12336 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12337 // If this is an insert of an extract from some other vector, include it.
12338 Value *VecOp = IEI->getOperand(0);
12339 Value *ScalarOp = IEI->getOperand(1);
12340 Value *IdxOp = IEI->getOperand(2);
12341
12342 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12343 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12344 EI->getOperand(0)->getType() == V->getType()) {
12345 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012346 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12347 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012348
12349 // Either the extracted from or inserted into vector must be RHSVec,
12350 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012351 if (EI->getOperand(0) == RHS || RHS == 0) {
12352 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012353 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012354 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012355 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012356 return V;
12357 }
12358
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012359 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012360 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12361 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012362 // Everything but the extracted element is replaced with the RHS.
12363 for (unsigned i = 0; i != NumElts; ++i) {
12364 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012365 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012366 }
12367 return V;
12368 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012369
12370 // If this insertelement is a chain that comes from exactly these two
12371 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012372 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12373 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012374 return EI->getOperand(0);
12375
Chris Lattnerefb47352006-04-15 01:39:45 +000012376 }
12377 }
12378 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012379 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012380
12381 // Otherwise, can't do anything fancy. Return an identity vector.
12382 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012383 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012384 return V;
12385}
12386
12387Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12388 Value *VecOp = IE.getOperand(0);
12389 Value *ScalarOp = IE.getOperand(1);
12390 Value *IdxOp = IE.getOperand(2);
12391
Chris Lattner599ded12007-04-09 01:11:16 +000012392 // Inserting an undef or into an undefined place, remove this.
12393 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12394 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012395
Chris Lattnerefb47352006-04-15 01:39:45 +000012396 // If the inserted element was extracted from some other vector, and if the
12397 // indexes are constant, try to turn this into a shufflevector operation.
12398 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12399 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12400 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012401 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012402 unsigned ExtractedIdx =
12403 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012404 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012405
12406 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12407 return ReplaceInstUsesWith(IE, VecOp);
12408
12409 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012410 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012411
12412 // If we are extracting a value from a vector, then inserting it right
12413 // back into the same place, just use the input vector.
12414 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12415 return ReplaceInstUsesWith(IE, VecOp);
12416
12417 // We could theoretically do this for ANY input. However, doing so could
12418 // turn chains of insertelement instructions into a chain of shufflevector
12419 // instructions, and right now we do not merge shufflevectors. As such,
12420 // only do this in a situation where it is clear that there is benefit.
12421 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12422 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12423 // the values of VecOp, except then one read from EIOp0.
12424 // Build a new shuffle mask.
12425 std::vector<Constant*> Mask;
12426 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012427 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012428 else {
12429 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012430 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012431 NumVectorElts));
12432 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012433 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012434 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012435 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012436 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012437 }
12438
12439 // If this insertelement isn't used by some other insertelement, turn it
12440 // (and any insertelements it points to), into one big shuffle.
12441 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12442 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012443 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012444 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012445 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012446 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012447 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012448 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012449 }
12450 }
12451 }
12452
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012453 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12454 APInt UndefElts(VWidth, 0);
12455 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12456 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12457 return &IE;
12458
Chris Lattnerefb47352006-04-15 01:39:45 +000012459 return 0;
12460}
12461
12462
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012463Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12464 Value *LHS = SVI.getOperand(0);
12465 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012466 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012467
12468 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012469
Chris Lattner867b99f2006-10-05 06:55:50 +000012470 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012471 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012472 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012473
Dan Gohman488fbfc2008-09-09 18:11:14 +000012474 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012475
12476 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12477 return 0;
12478
Evan Cheng388df622009-02-03 10:05:09 +000012479 APInt UndefElts(VWidth, 0);
12480 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12481 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012482 LHS = SVI.getOperand(0);
12483 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012484 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012485 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012486
Chris Lattner863bcff2006-05-25 23:48:38 +000012487 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12488 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12489 if (LHS == RHS || isa<UndefValue>(LHS)) {
12490 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012491 // shuffle(undef,undef,mask) -> undef.
12492 return ReplaceInstUsesWith(SVI, LHS);
12493 }
12494
Chris Lattner863bcff2006-05-25 23:48:38 +000012495 // Remap any references to RHS to use LHS.
12496 std::vector<Constant*> Elts;
12497 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012498 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012499 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012500 else {
12501 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012502 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012503 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012504 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012505 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012506 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012507 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012508 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012509 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012510 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012511 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012512 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012513 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012514 LHS = SVI.getOperand(0);
12515 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012516 MadeChange = true;
12517 }
12518
Chris Lattner7b2e27922006-05-26 00:29:06 +000012519 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012520 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012521
Chris Lattner863bcff2006-05-25 23:48:38 +000012522 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12523 if (Mask[i] >= e*2) continue; // Ignore undef values.
12524 // Is this an identity shuffle of the LHS value?
12525 isLHSID &= (Mask[i] == i);
12526
12527 // Is this an identity shuffle of the RHS value?
12528 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012529 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012530
Chris Lattner863bcff2006-05-25 23:48:38 +000012531 // Eliminate identity shuffles.
12532 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12533 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012534
Chris Lattner7b2e27922006-05-26 00:29:06 +000012535 // If the LHS is a shufflevector itself, see if we can combine it with this
12536 // one without producing an unusual shuffle. Here we are really conservative:
12537 // we are absolutely afraid of producing a shuffle mask not in the input
12538 // program, because the code gen may not be smart enough to turn a merged
12539 // shuffle into two specific shuffles: it may produce worse code. As such,
12540 // we only merge two shuffles if the result is one of the two input shuffle
12541 // masks. In this case, merging the shuffles just removes one instruction,
12542 // which we know is safe. This is good for things like turning:
12543 // (splat(splat)) -> splat.
12544 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12545 if (isa<UndefValue>(RHS)) {
12546 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12547
12548 std::vector<unsigned> NewMask;
12549 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12550 if (Mask[i] >= 2*e)
12551 NewMask.push_back(2*e);
12552 else
12553 NewMask.push_back(LHSMask[Mask[i]]);
12554
12555 // If the result mask is equal to the src shuffle or this shuffle mask, do
12556 // the replacement.
12557 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012558 unsigned LHSInNElts =
12559 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012560 std::vector<Constant*> Elts;
12561 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012562 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012563 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012564 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012565 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012566 }
12567 }
12568 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12569 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012570 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012571 }
12572 }
12573 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012574
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012575 return MadeChange ? &SVI : 0;
12576}
12577
12578
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012579
Chris Lattnerea1c4542004-12-08 23:43:58 +000012580
12581/// TryToSinkInstruction - Try to move the specified instruction from its
12582/// current block into the beginning of DestBlock, which can only happen if it's
12583/// safe to move the instruction past all of the instructions between it and the
12584/// end of its block.
12585static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12586 assert(I->hasOneUse() && "Invariants didn't hold!");
12587
Chris Lattner108e9022005-10-27 17:13:11 +000012588 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012589 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012590 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012591
Chris Lattnerea1c4542004-12-08 23:43:58 +000012592 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012593 if (isa<AllocaInst>(I) && I->getParent() ==
12594 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012595 return false;
12596
Chris Lattner96a52a62004-12-09 07:14:34 +000012597 // We can only sink load instructions if there is nothing between the load and
12598 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012599 if (I->mayReadFromMemory()) {
12600 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012601 Scan != E; ++Scan)
12602 if (Scan->mayWriteToMemory())
12603 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012604 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012605
Dan Gohman02dea8b2008-05-23 21:05:58 +000012606 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012607
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012608 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012609 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012610 ++NumSunkInst;
12611 return true;
12612}
12613
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012614
12615/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12616/// all reachable code to the worklist.
12617///
12618/// This has a couple of tricks to make the code faster and more powerful. In
12619/// particular, we constant fold and DCE instructions as we go, to avoid adding
12620/// them to the worklist (this significantly speeds up instcombine on code where
12621/// many instructions are dead or constant). Additionally, if we find a branch
12622/// whose condition is a known constant, we only visit the reachable successors.
12623///
12624static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012625 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012626 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012627 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012628 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012629 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012630
Chris Lattner2c7718a2007-03-23 19:17:18 +000012631 while (!Worklist.empty()) {
12632 BB = Worklist.back();
12633 Worklist.pop_back();
12634
12635 // We have now visited this block! If we've already been here, ignore it.
12636 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012637
12638 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012639 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12640 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012641
Chris Lattner2c7718a2007-03-23 19:17:18 +000012642 // DCE instruction if trivially dead.
12643 if (isInstructionTriviallyDead(Inst)) {
12644 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012645 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012646 Inst->eraseFromParent();
12647 continue;
12648 }
12649
12650 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012651 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012652 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12653 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012654 Inst->replaceAllUsesWith(C);
12655 ++NumConstProp;
12656 Inst->eraseFromParent();
12657 continue;
12658 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012659
Devang Patel7fe1dec2008-11-19 18:56:50 +000012660 // If there are two consecutive llvm.dbg.stoppoint calls then
12661 // it is likely that the optimizer deleted code in between these
12662 // two intrinsics.
12663 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12664 if (DBI_Next) {
12665 if (DBI_Prev
12666 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12667 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012668 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012669 DBI_Prev->eraseFromParent();
12670 }
12671 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012672 } else {
12673 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012674 }
12675
Chris Lattner7a1e9242009-08-30 06:13:40 +000012676 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012677 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012678
12679 // Recursively visit successors. If this is a branch or switch on a
12680 // constant, only visit the reachable successor.
12681 TerminatorInst *TI = BB->getTerminator();
12682 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12683 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12684 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012685 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012686 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012687 continue;
12688 }
12689 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12690 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12691 // See if this is an explicit destination.
12692 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12693 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012694 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012695 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012696 continue;
12697 }
12698
12699 // Otherwise it is the default destination.
12700 Worklist.push_back(SI->getSuccessor(0));
12701 continue;
12702 }
12703 }
12704
12705 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12706 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012707 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012708}
12709
Chris Lattnerec9c3582007-03-03 02:04:50 +000012710bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012711 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012712 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012713
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012714 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12715 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012716
Chris Lattnerb3d59702005-07-07 20:40:38 +000012717 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012718 // Do a depth-first traversal of the function, populate the worklist with
12719 // the reachable instructions. Ignore blocks that are not reachable. Keep
12720 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012721 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012722 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012723
Chris Lattnerb3d59702005-07-07 20:40:38 +000012724 // Do a quick scan over the function. If we find any blocks that are
12725 // unreachable, remove any instructions inside of them. This prevents
12726 // the instcombine code from having to deal with some bad special cases.
12727 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12728 if (!Visited.count(BB)) {
12729 Instruction *Term = BB->getTerminator();
12730 while (Term != BB->begin()) { // Remove instrs bottom-up
12731 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012732
Chris Lattnerbdff5482009-08-23 04:37:46 +000012733 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012734 // A debug intrinsic shouldn't force another iteration if we weren't
12735 // going to do one without it.
12736 if (!isa<DbgInfoIntrinsic>(I)) {
12737 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012738 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012739 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012740 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012741 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012742 I->eraseFromParent();
12743 }
12744 }
12745 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012746
Chris Lattner873ff012009-08-30 05:55:36 +000012747 while (!Worklist.isEmpty()) {
12748 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012749 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012750
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012751 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012752 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012753 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012754 EraseInstFromFunction(*I);
12755 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012756 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012757 continue;
12758 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012759
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012760 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012761 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012762 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012763
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012764 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012765 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012766 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012767 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012768 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012769 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012770 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012771
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012772 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012773 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012774 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12775 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012776 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12777 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012778 if (NewC != CE) {
12779 i->set(NewC);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012780 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012781 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012782 }
12783
Chris Lattnerea1c4542004-12-08 23:43:58 +000012784 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012785 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012786 BasicBlock *BB = I->getParent();
12787 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12788 if (UserParent != BB) {
12789 bool UserIsSuccessor = false;
12790 // See if the user is one of our successors.
12791 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12792 if (*SI == UserParent) {
12793 UserIsSuccessor = true;
12794 break;
12795 }
12796
12797 // If the user is one of our immediate successors, and if that successor
12798 // only has us as a predecessors (we'd have to split the critical edge
12799 // otherwise), we can keep going.
12800 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12801 next(pred_begin(UserParent)) == pred_end(UserParent))
12802 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012803 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012804 }
12805 }
12806
Chris Lattner74381062009-08-30 07:44:24 +000012807 // Now that we have an instruction, try combining it to simplify it.
12808 Builder->SetInsertPoint(I->getParent(), I);
12809
Reid Spencera9b81012007-03-26 17:44:01 +000012810#ifndef NDEBUG
12811 std::string OrigI;
12812#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012813 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012814
Chris Lattner90ac28c2002-08-02 19:29:35 +000012815 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012816 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012817 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012818 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012819 DEBUG(errs() << "IC: Old = " << *I << '\n'
12820 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012821
Chris Lattnerf523d062004-06-09 05:08:07 +000012822 // Everything uses the new instruction now.
12823 I->replaceAllUsesWith(Result);
12824
12825 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012826 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012827 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012828
Chris Lattner6934a042007-02-11 01:23:03 +000012829 // Move the name to the new instruction first.
12830 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012831
12832 // Insert the new instruction into the basic block...
12833 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012834 BasicBlock::iterator InsertPos = I;
12835
12836 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12837 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12838 ++InsertPos;
12839
12840 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012841
Chris Lattner7a1e9242009-08-30 06:13:40 +000012842 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012843 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012844#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012845 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12846 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012847#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012848
Chris Lattner90ac28c2002-08-02 19:29:35 +000012849 // If the instruction was modified, it's possible that it is now dead.
12850 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012851 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012852 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012853 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012854 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012855 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012856 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012857 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012858 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012859 }
12860 }
12861
Chris Lattner873ff012009-08-30 05:55:36 +000012862 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012863 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012864}
12865
Chris Lattnerec9c3582007-03-03 02:04:50 +000012866
12867bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012868 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012869 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012870
Chris Lattner74381062009-08-30 07:44:24 +000012871
12872 /// Builder - This is an IRBuilder that automatically inserts new
12873 /// instructions into the worklist when they are created.
12874 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12875 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12876 InstCombineIRInserter(Worklist));
12877 Builder = &TheBuilder;
12878
Chris Lattnerec9c3582007-03-03 02:04:50 +000012879 bool EverMadeChange = false;
12880
12881 // Iterate while there is work to do.
12882 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012883 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012884 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012885
12886 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012887 return EverMadeChange;
12888}
12889
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012890FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012891 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012892}