blob: be88d299ded00f7fe8e84440c82291b58373d53d [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 Lattner5d1704d2009-09-27 19:57:57 +0000387 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
388 // which has a PHI node as operand #0, see if we can fold the instruction
389 // into the PHI (which is only possible if all operands to the PHI are
390 // constants).
Chris Lattner4e998b22004-09-29 05:07:12 +0000391 Instruction *FoldOpIntoPhi(Instruction &I);
392
Chris Lattnerbac32862004-11-14 19:13:23 +0000393 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
394 // operator and they all are only used by the PHI, PHI together their
395 // inputs, and do the operation once, to the result of the PHI.
396 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000397 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000398 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
399
Chris Lattner7da52b22006-11-01 04:51:18 +0000400
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000401 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
402 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000403
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000404 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000405 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000406 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000407 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000408 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000409 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000410 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000411 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000412 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000413
Chris Lattnerafe91a52006-06-15 19:07:26 +0000414
Reid Spencerc55b2432006-12-13 18:21:21 +0000415 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000416
Dan Gohman6de29f82009-06-15 22:12:54 +0000417 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000418 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000419 unsigned GetOrEnforceKnownAlignment(Value *V,
420 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000421
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000422 };
Chris Lattner873ff012009-08-30 05:55:36 +0000423} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000424
Dan Gohman844731a2008-05-13 00:00:25 +0000425char InstCombiner::ID = 0;
426static RegisterPass<InstCombiner>
427X("instcombine", "Combine redundant instructions");
428
Chris Lattner4f98c562003-03-10 21:43:22 +0000429// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000430// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000431static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000432 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000433 if (BinaryOperator::isNeg(V) ||
434 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000435 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000436 return 3;
437 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000438 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000439 if (isa<Argument>(V)) return 3;
440 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000441}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000442
Chris Lattnerc8802d22003-03-11 00:12:48 +0000443// isOnlyUse - Return true if this instruction will be deleted if we stop using
444// it.
445static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000446 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000447}
448
Chris Lattner4cb170c2004-02-23 06:38:22 +0000449// getPromotedType - Return the specified type promoted as it would be to pass
450// though a va_arg area...
451static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000452 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
453 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000454 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000455 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000456 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000457}
458
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000459/// getBitCastOperand - If the specified operand is a CastInst, a constant
460/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
461/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000462static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000463 if (Operator *O = dyn_cast<Operator>(V)) {
464 if (O->getOpcode() == Instruction::BitCast)
465 return O->getOperand(0);
466 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
467 if (GEP->hasAllZeroIndices())
468 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000469 }
Chris Lattnereed48272005-09-13 00:40:14 +0000470 return 0;
471}
472
Reid Spencer3da59db2006-11-27 01:05:10 +0000473/// This function is a wrapper around CastInst::isEliminableCastPair. It
474/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000475static Instruction::CastOps
476isEliminableCastPair(
477 const CastInst *CI, ///< The first cast instruction
478 unsigned opcode, ///< The opcode of the second cast instruction
479 const Type *DstTy, ///< The target type for the second cast instruction
480 TargetData *TD ///< The target data for pointer size
481) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000482
Reid Spencer3da59db2006-11-27 01:05:10 +0000483 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
484 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000485
Reid Spencer3da59db2006-11-27 01:05:10 +0000486 // Get the opcodes of the two Cast instructions
487 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
488 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000489
Chris Lattnera0e69692009-03-24 18:35:40 +0000490 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000491 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000492 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000493
494 // We don't want to form an inttoptr or ptrtoint that converts to an integer
495 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000496 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000497 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000498 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000499 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000500 Res = 0;
501
502 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000503}
504
505/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
506/// in any code being generated. It does not require codegen if V is simple
507/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000508static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
509 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000510 if (V->getType() == Ty || isa<Constant>(V)) return false;
511
Chris Lattner01575b72006-05-25 23:24:33 +0000512 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000513 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000514 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000515 return false;
516 return true;
517}
518
Chris Lattner4f98c562003-03-10 21:43:22 +0000519// SimplifyCommutative - This performs a few simplifications for commutative
520// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000521//
Chris Lattner4f98c562003-03-10 21:43:22 +0000522// 1. Order operands such that they are listed from right (least complex) to
523// left (most complex). This puts constants before unary operators before
524// binary operators.
525//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000526// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
527// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000528//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000530 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000531 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000532 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000533
Chris Lattner4f98c562003-03-10 21:43:22 +0000534 if (!I.isAssociative()) return Changed;
535 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
537 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
538 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000539 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000540 cast<Constant>(I.getOperand(1)),
541 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000542 I.setOperand(0, Op->getOperand(0));
543 I.setOperand(1, Folded);
544 return true;
545 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
546 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
547 isOnlyUse(Op) && isOnlyUse(Op1)) {
548 Constant *C1 = cast<Constant>(Op->getOperand(1));
549 Constant *C2 = cast<Constant>(Op1->getOperand(1));
550
551 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000552 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000553 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000554 Op1->getOperand(0),
555 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000556 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 I.setOperand(0, New);
558 I.setOperand(1, Folded);
559 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000560 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000561 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000562 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000563}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000564
Reid Spencere4d87aa2006-12-23 06:05:41 +0000565/// SimplifyCompare - For a CmpInst this function just orders the operands
566/// so that theyare listed from right (least complex) to left (most complex).
567/// This puts constants before unary operators before binary operators.
568bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000569 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000570 return false;
571 I.swapOperands();
572 // Compare instructions are not associative so there's nothing else we can do.
573 return true;
574}
575
Chris Lattner8d969642003-03-10 23:06:50 +0000576// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
577// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000578//
Dan Gohman186a6362009-08-12 16:04:34 +0000579static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000580 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000581 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000582
Chris Lattner0ce85802004-12-14 20:08:06 +0000583 // Constants can be considered to be negated values if they can be folded.
584 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000585 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000586
587 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
588 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000589 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000590
Chris Lattner8d969642003-03-10 23:06:50 +0000591 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000592}
593
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000594// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
595// instruction if the LHS is a constant negative zero (which is the 'negate'
596// form).
597//
Dan Gohman186a6362009-08-12 16:04:34 +0000598static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000599 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000600 return BinaryOperator::getFNegArgument(V);
601
602 // Constants can be considered to be negated values if they can be folded.
603 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000605
606 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
607 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000608 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000609
610 return 0;
611}
612
Dan Gohman186a6362009-08-12 16:04:34 +0000613static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000614 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000615 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000616
617 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000618 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000619 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000620 return 0;
621}
622
Chris Lattnerc8802d22003-03-11 00:12:48 +0000623// dyn_castFoldableMul - If this value is a multiply that can be folded into
624// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000625// non-constant operand of the multiply, and set CST to point to the multiplier.
626// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000627//
Dan Gohman186a6362009-08-12 16:04:34 +0000628static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000629 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000630 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000631 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000632 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000633 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000634 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000635 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000636 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000637 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000638 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000639 CST = ConstantInt::get(V->getType()->getContext(),
640 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000641 return I->getOperand(0);
642 }
643 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000644 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000645}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000646
Reid Spencer7177c3a2007-03-25 05:33:51 +0000647/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000648static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000649 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000650 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000651}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000652/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000653static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000654 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000655 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000656}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000657/// MultiplyOverflows - True if the multiply can not be expressed in an int
658/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000659static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000660 uint32_t W = C1->getBitWidth();
661 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
662 if (sign) {
663 LHSExt.sext(W * 2);
664 RHSExt.sext(W * 2);
665 } else {
666 LHSExt.zext(W * 2);
667 RHSExt.zext(W * 2);
668 }
669
670 APInt MulExt = LHSExt * RHSExt;
671
672 if (sign) {
673 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
674 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
675 return MulExt.slt(Min) || MulExt.sgt(Max);
676 } else
677 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
678}
Chris Lattner955f3312004-09-28 21:48:02 +0000679
Reid Spencere7816b52007-03-08 01:52:58 +0000680
Chris Lattner255d8912006-02-11 09:31:47 +0000681/// ShrinkDemandedConstant - Check to see if the specified operand of the
682/// specified instruction is a constant integer. If so, check to see if there
683/// are any bits set in the constant that are not demanded. If so, shrink the
684/// constant and return true.
685static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000686 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000687 assert(I && "No instruction?");
688 assert(OpNo < I->getNumOperands() && "Operand index too large");
689
690 // If the operand is not a constant integer, nothing to do.
691 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
692 if (!OpC) return false;
693
694 // If there are no bits set that aren't demanded, nothing to do.
695 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
696 if ((~Demanded & OpC->getValue()) == 0)
697 return false;
698
699 // This instruction is producing bits that are not demanded. Shrink the RHS.
700 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000701 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000702 return true;
703}
704
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000705// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
706// set of known zero and one bits, compute the maximum and minimum values that
707// could have the specified known zero and known one bits, returning them in
708// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000709static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000710 const APInt& KnownOne,
711 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000712 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
713 KnownZero.getBitWidth() == Min.getBitWidth() &&
714 KnownZero.getBitWidth() == Max.getBitWidth() &&
715 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000716 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000718 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
719 // bit if it is unknown.
720 Min = KnownOne;
721 Max = KnownOne|UnknownBits;
722
Dan Gohman1c8491e2009-04-25 17:12:48 +0000723 if (UnknownBits.isNegative()) { // Sign bit is unknown
724 Min.set(Min.getBitWidth()-1);
725 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000727}
728
729// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
730// a set of known zero and one bits, compute the maximum and minimum values that
731// could have the specified known zero and known one bits, returning them in
732// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000733static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000734 const APInt &KnownOne,
735 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000736 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
737 KnownZero.getBitWidth() == Min.getBitWidth() &&
738 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000739 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000740 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741
742 // The minimum value is when the unknown bits are all zeros.
743 Min = KnownOne;
744 // The maximum value is when the unknown bits are all ones.
745 Max = KnownOne|UnknownBits;
746}
Chris Lattner255d8912006-02-11 09:31:47 +0000747
Chris Lattner886ab6c2009-01-31 08:15:18 +0000748/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
749/// SimplifyDemandedBits knows about. See if the instruction has any
750/// properties that allow us to simplify its operands.
751bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000752 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000753 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
754 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
755
756 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
757 KnownZero, KnownOne, 0);
758 if (V == 0) return false;
759 if (V == &Inst) return true;
760 ReplaceInstUsesWith(Inst, V);
761 return true;
762}
763
764/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
765/// specified instruction operand if possible, updating it in place. It returns
766/// true if it made any change and false otherwise.
767bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
768 APInt &KnownZero, APInt &KnownOne,
769 unsigned Depth) {
770 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
771 KnownZero, KnownOne, Depth);
772 if (NewVal == 0) return false;
773 U.set(NewVal);
774 return true;
775}
776
777
778/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
779/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000780/// that only the bits set in DemandedMask of the result of V are ever used
781/// downstream. Consequently, depending on the mask and V, it may be possible
782/// to replace V with a constant or one of its operands. In such cases, this
783/// function does the replacement and returns true. In all other cases, it
784/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000785/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000786/// to be zero in the expression. These are provided to potentially allow the
787/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
788/// the expression. KnownOne and KnownZero always follow the invariant that
789/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
790/// the bits in KnownOne and KnownZero may only be accurate for those bits set
791/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
792/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000793///
794/// This returns null if it did not change anything and it permits no
795/// simplification. This returns V itself if it did some simplification of V's
796/// operands based on the information about what bits are demanded. This returns
797/// some other non-null value if it found out that V is equal to another value
798/// in the context where the specified bits are demanded, but not for all users.
799Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
800 APInt &KnownZero, APInt &KnownOne,
801 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000802 assert(V != 0 && "Null pointer of Value???");
803 assert(Depth <= 6 && "Limit Search Depth");
804 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000805 const Type *VTy = V->getType();
806 assert((TD || !isa<PointerType>(VTy)) &&
807 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000808 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
809 (!VTy->isIntOrIntVector() ||
810 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000811 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000813 "Value *V, DemandedMask, KnownZero and KnownOne "
814 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000815 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
816 // We know all of the bits for a constant!
817 KnownOne = CI->getValue() & DemandedMask;
818 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000819 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000821 if (isa<ConstantPointerNull>(V)) {
822 // We know all of the bits for a constant!
823 KnownOne.clear();
824 KnownZero = DemandedMask;
825 return 0;
826 }
827
Chris Lattner08d2cc72009-01-31 07:26:06 +0000828 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000829 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000830 if (DemandedMask == 0) { // Not demanding any bits from V.
831 if (isa<UndefValue>(V))
832 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000833 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000834 }
835
Chris Lattner4598c942009-01-31 08:24:16 +0000836 if (Depth == 6) // Limit search depth.
837 return 0;
838
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000839 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
840 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
841
Dan Gohman1c8491e2009-04-25 17:12:48 +0000842 Instruction *I = dyn_cast<Instruction>(V);
843 if (!I) {
844 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
845 return 0; // Only analyze instructions.
846 }
847
Chris Lattner4598c942009-01-31 08:24:16 +0000848 // If there are multiple uses of this value and we aren't at the root, then
849 // we can't do any simplifications of the operands, because DemandedMask
850 // only reflects the bits demanded by *one* of the users.
851 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000852 // Despite the fact that we can't simplify this instruction in all User's
853 // context, we can at least compute the knownzero/knownone bits, and we can
854 // do simplifications that apply to *just* the one user if we know that
855 // this instruction has a simpler value in that context.
856 if (I->getOpcode() == Instruction::And) {
857 // If either the LHS or the RHS are Zero, the result is zero.
858 ComputeMaskedBits(I->getOperand(1), DemandedMask,
859 RHSKnownZero, RHSKnownOne, Depth+1);
860 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
861 LHSKnownZero, LHSKnownOne, Depth+1);
862
863 // If all of the demanded bits are known 1 on one side, return the other.
864 // These bits cannot contribute to the result of the 'and' in this
865 // context.
866 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
867 (DemandedMask & ~LHSKnownZero))
868 return I->getOperand(0);
869 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
870 (DemandedMask & ~RHSKnownZero))
871 return I->getOperand(1);
872
873 // If all of the demanded bits in the inputs are known zeros, return zero.
874 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000875 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000876
877 } else if (I->getOpcode() == Instruction::Or) {
878 // We can simplify (X|Y) -> X or Y in the user's context if we know that
879 // only bits from X or Y are demanded.
880
881 // If either the LHS or the RHS are One, the result is One.
882 ComputeMaskedBits(I->getOperand(1), DemandedMask,
883 RHSKnownZero, RHSKnownOne, Depth+1);
884 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
885 LHSKnownZero, LHSKnownOne, Depth+1);
886
887 // If all of the demanded bits are known zero on one side, return the
888 // other. These bits cannot contribute to the result of the 'or' in this
889 // context.
890 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
891 (DemandedMask & ~LHSKnownOne))
892 return I->getOperand(0);
893 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
894 (DemandedMask & ~RHSKnownOne))
895 return I->getOperand(1);
896
897 // If all of the potentially set bits on one side are known to be set on
898 // the other side, just use the 'other' side.
899 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
900 (DemandedMask & (~RHSKnownZero)))
901 return I->getOperand(0);
902 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
903 (DemandedMask & (~LHSKnownZero)))
904 return I->getOperand(1);
905 }
906
Chris Lattner4598c942009-01-31 08:24:16 +0000907 // Compute the KnownZero/KnownOne bits to simplify things downstream.
908 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
909 return 0;
910 }
911
912 // If this is the root being simplified, allow it to have multiple uses,
913 // just set the DemandedMask to all bits so that we can try to simplify the
914 // operands. This allows visitTruncInst (for example) to simplify the
915 // operand of a trunc without duplicating all the logic below.
916 if (Depth == 0 && !V->hasOneUse())
917 DemandedMask = APInt::getAllOnesValue(BitWidth);
918
Reid Spencer8cb68342007-03-12 17:25:59 +0000919 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000920 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000921 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000922 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 case Instruction::And:
924 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000925 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
926 RHSKnownZero, RHSKnownOne, Depth+1) ||
927 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000928 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000929 return I;
930 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
931 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000932
933 // If all of the demanded bits are known 1 on one side, return the other.
934 // These bits cannot contribute to the result of the 'and'.
935 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
936 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000937 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
939 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000941
942 // If all of the demanded bits in the inputs are known zeros, return zero.
943 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000944 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000945
946 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000947 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000949
950 // Output known-1 bits are only known if set in both the LHS & RHS.
951 RHSKnownOne &= LHSKnownOne;
952 // Output known-0 are known to be clear if zero in either the LHS | RHS.
953 RHSKnownZero |= LHSKnownZero;
954 break;
955 case Instruction::Or:
956 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
958 RHSKnownZero, RHSKnownOne, Depth+1) ||
959 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000960 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I;
962 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
963 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // If all of the demanded bits are known zero on one side, return the other.
966 // These bits cannot contribute to the result of the 'or'.
967 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
968 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000970 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
971 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000973
974 // If all of the potentially set bits on one side are known to be set on
975 // the other side, just use the 'other' side.
976 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
977 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
980 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000981 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000982
983 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000984 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000986
987 // Output known-0 bits are only known if clear in both the LHS & RHS.
988 RHSKnownZero &= LHSKnownZero;
989 // Output known-1 are known to be set if set in either the LHS | RHS.
990 RHSKnownOne |= LHSKnownOne;
991 break;
992 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
994 RHSKnownZero, RHSKnownOne, Depth+1) ||
995 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000996 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I;
998 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
999 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // If all of the demanded bits are known zero on one side, return the other.
1002 // These bits cannot contribute to the result of the 'xor'.
1003 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001007
1008 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1009 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1010 (RHSKnownOne & LHSKnownOne);
1011 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1012 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1013 (RHSKnownOne & LHSKnownZero);
1014
1015 // If all of the demanded bits are known to be zero on one side or the
1016 // other, turn this into an *inclusive* or.
1017 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001018 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1019 Instruction *Or =
1020 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1021 I->getName());
1022 return InsertNewInstBefore(Or, *I);
1023 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001024
1025 // If all of the demanded bits on one side are known, and all of the set
1026 // bits on that side are also known to be set on the other side, turn this
1027 // into an AND, as we know the bits will be cleared.
1028 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1029 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1030 // all known
1031 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001032 Constant *AndC = Constant::getIntegerValue(VTy,
1033 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001034 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001035 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 }
1038 }
1039
1040 // If the RHS is a constant, see if we can simplify it.
1041 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001042 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001044
1045 RHSKnownZero = KnownZeroOut;
1046 RHSKnownOne = KnownOneOut;
1047 break;
1048 }
1049 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1051 RHSKnownZero, RHSKnownOne, Depth+1) ||
1052 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 return I;
1055 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1056 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001057
1058 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001059 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1060 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001061 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001062
1063 // Only known if known in both the LHS and RHS.
1064 RHSKnownOne &= LHSKnownOne;
1065 RHSKnownZero &= LHSKnownZero;
1066 break;
1067 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001068 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001069 DemandedMask.zext(truncBf);
1070 RHSKnownZero.zext(truncBf);
1071 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001072 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001073 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001074 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001075 DemandedMask.trunc(BitWidth);
1076 RHSKnownZero.trunc(BitWidth);
1077 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001079 break;
1080 }
1081 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001082 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001084
1085 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1086 if (const VectorType *SrcVTy =
1087 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1088 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1089 // Don't touch a bitcast between vectors of different element counts.
1090 return false;
1091 } else
1092 // Don't touch a scalar-to-vector bitcast.
1093 return false;
1094 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1095 // Don't touch a vector-to-scalar bitcast.
1096 return false;
1097
Chris Lattner886ab6c2009-01-31 08:15:18 +00001098 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001099 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 return I;
1101 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001102 break;
1103 case Instruction::ZExt: {
1104 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001105 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001106
Zhou Shengd48653a2007-03-29 04:45:55 +00001107 DemandedMask.trunc(SrcBitWidth);
1108 RHSKnownZero.trunc(SrcBitWidth);
1109 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001111 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 DemandedMask.zext(BitWidth);
1114 RHSKnownZero.zext(BitWidth);
1115 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001116 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001117 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 break;
1120 }
1121 case Instruction::SExt: {
1122 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001123 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001124
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001126 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001127
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 // If any of the sign extended bits are demanded, we know that the sign
1130 // bit is demanded.
1131 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001132 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001133
Zhou Shengd48653a2007-03-29 04:45:55 +00001134 InputDemandedBits.trunc(SrcBitWidth);
1135 RHSKnownZero.trunc(SrcBitWidth);
1136 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001137 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001139 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001140 InputDemandedBits.zext(BitWidth);
1141 RHSKnownZero.zext(BitWidth);
1142 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
1145 // If the sign bit of the input is known set or clear, then we know the
1146 // top bits of the result.
1147
1148 // If the input sign bit is known zero, or if the NewBits are not demanded
1149 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001152 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1153 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001154 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001156 }
1157 break;
1158 }
1159 case Instruction::Add: {
1160 // Figure out what the input bits are. If the top bits of the and result
1161 // are not demanded, then the add doesn't demand them from its input
1162 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001164
1165 // If there is a constant on the RHS, there are a variety of xformations
1166 // we can do.
1167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1168 // If null, this should be simplified elsewhere. Some of the xforms here
1169 // won't work if the RHS is zero.
1170 if (RHS->isZero())
1171 break;
1172
1173 // If the top bit of the output is demanded, demand everything from the
1174 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001175 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001178 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
1182 // If the RHS of the add has bits set that can't affect the input, reduce
1183 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001184 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
1187 // Avoid excess work.
1188 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1189 break;
1190
1191 // Turn it into OR if input bits are zero.
1192 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1193 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001194 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001196 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001197 }
1198
1199 // We can say something about the output known-zero and known-one bits,
1200 // depending on potential carries from the input constant and the
1201 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1202 // bits set and the RHS constant is 0x01001, then we know we have a known
1203 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1204
1205 // To compute this, we first compute the potential carry bits. These are
1206 // the bits which may be modified. I'm not aware of a better way to do
1207 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001208 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001209 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001210
1211 // Now that we know which bits have carries, compute the known-1/0 sets.
1212
1213 // Bits are known one if they are known zero in one operand and one in the
1214 // other, and there is no input carry.
1215 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1216 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1217
1218 // Bits are known zero if they are known zero in both operands and there
1219 // is no input carry.
1220 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1221 } else {
1222 // If the high-bits of this ADD are not demanded, then it does not demand
1223 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 // Right fill the mask of bits for this ADD to demand the most
1226 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001227 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1229 LHSKnownZero, LHSKnownOne, Depth+1) ||
1230 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001232 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 }
1234 }
1235 break;
1236 }
1237 case Instruction::Sub:
1238 // If the high-bits of this SUB are not demanded, then it does not demand
1239 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001240 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 // Right fill the mask of bits for this SUB to demand the most
1242 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001243 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246 LHSKnownZero, LHSKnownOne, Depth+1) ||
1247 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001251 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1252 // the known zeros and ones.
1253 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 break;
1255 case Instruction::Shl:
1256 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001257 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001258 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001259 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 return I;
1262 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001263 RHSKnownZero <<= ShiftAmt;
1264 RHSKnownOne <<= ShiftAmt;
1265 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001266 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001267 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 }
1269 break;
1270 case Instruction::LShr:
1271 // For a logical shift right
1272 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001273 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001276 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001277 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001279 return I;
1280 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1282 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001283 if (ShiftAmt) {
1284 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001286 RHSKnownZero |= HighBits; // high bits known zero.
1287 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 }
1289 break;
1290 case Instruction::AShr:
1291 // If this is an arithmetic shift right and only the low-bit is set, we can
1292 // always convert this into a logical shr, even if the shift amount is
1293 // variable. The low bit of the shift cannot be an input sign bit unless
1294 // the shift amount is >= the size of the datatype, which is undefined.
1295 if (DemandedMask == 1) {
1296 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001297 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001299 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001301
1302 // If the sign bit is the only bit demanded by this ashr, then there is no
1303 // need to do it, the shift doesn't change the high bit.
1304 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306
1307 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001308 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001309
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001311 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001312 // If any of the "high bits" are demanded, we should set the sign bit as
1313 // demanded.
1314 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1315 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 return I;
1319 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001321 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1323 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1324
1325 // Handle the sign bits.
1326 APInt SignBit(APInt::getSignBit(BitWidth));
1327 // Adjust to where it is now in the mask.
1328 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1329
1330 // If the input sign bit is known to be zero, or if none of the top bits
1331 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001332 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 (HighBits & ~DemandedMask) == HighBits) {
1334 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001338 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1339 RHSKnownOne |= HighBits;
1340 }
1341 }
1342 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001343 case Instruction::SRem:
1344 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001345 APInt RA = Rem->getValue().abs();
1346 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001347 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001348 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001349
Nick Lewycky8e394322008-11-02 02:41:50 +00001350 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001351 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001355
1356 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1357 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001358
1359 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001360
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362 }
1363 }
1364 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001365 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001366 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1367 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001368 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1369 KnownZero2, KnownOne2, Depth+1) ||
1370 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001371 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001372 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001373
Chris Lattner455e9ab2009-01-21 18:09:24 +00001374 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001375 Leaders = std::max(Leaders,
1376 KnownZero2.countLeadingOnes());
1377 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001378 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001380 case Instruction::Call:
1381 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1382 switch (II->getIntrinsicID()) {
1383 default: break;
1384 case Intrinsic::bswap: {
1385 // If the only bits demanded come from one byte of the bswap result,
1386 // just shift the input byte into position to eliminate the bswap.
1387 unsigned NLZ = DemandedMask.countLeadingZeros();
1388 unsigned NTZ = DemandedMask.countTrailingZeros();
1389
1390 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1391 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1392 // have 14 leading zeros, round to 8.
1393 NLZ &= ~7;
1394 NTZ &= ~7;
1395 // If we need exactly one byte, we can do this transformation.
1396 if (BitWidth-NLZ-NTZ == 8) {
1397 unsigned ResultBit = NTZ;
1398 unsigned InputBit = BitWidth-NTZ-8;
1399
1400 // Replace this with either a left or right shift to get the byte into
1401 // the right place.
1402 Instruction *NewVal;
1403 if (InputBit > ResultBit)
1404 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001405 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001406 else
1407 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001408 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001409 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001410 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001411 }
1412
1413 // TODO: Could compute known zero/one bits based on the input.
1414 break;
1415 }
1416 }
1417 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001418 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001419 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001420 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001421
1422 // If the client is only demanding bits that we know, return the known
1423 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001424 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1425 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001426 return false;
1427}
1428
Chris Lattner867b99f2006-10-05 06:55:50 +00001429
Mon P Wangaeb06d22008-11-10 04:46:22 +00001430/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001431/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001432/// actually used by the caller. This method analyzes which elements of the
1433/// operand are undef and returns that information in UndefElts.
1434///
1435/// If the information about demanded elements can be used to simplify the
1436/// operation, the operation is simplified, then the resultant value is
1437/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001438Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1439 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001440 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001441 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001442 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001443 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001444
1445 if (isa<UndefValue>(V)) {
1446 // If the entire vector is undefined, just return this info.
1447 UndefElts = EltMask;
1448 return 0;
1449 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1450 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001451 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001453
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001455 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1456 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001457 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001458
1459 std::vector<Constant*> Elts;
1460 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001461 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001463 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1465 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001466 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 } else { // Otherwise, defined.
1468 Elts.push_back(CP->getOperand(i));
1469 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001470
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001472 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 return NewCP != CP ? NewCP : 0;
1474 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001475 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001476 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001477
1478 // Check if this is identity. If so, return 0 since we are not simplifying
1479 // anything.
1480 if (DemandedElts == ((1ULL << VWidth) -1))
1481 return 0;
1482
Reid Spencer9d6565a2007-02-15 02:26:10 +00001483 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001484 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001485 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001487 for (unsigned i = 0; i != VWidth; ++i) {
1488 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1489 Elts.push_back(Elt);
1490 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001492 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001493 }
1494
Dan Gohman488fbfc2008-09-09 18:11:14 +00001495 // Limit search depth.
1496 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001497 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001498
1499 // If multiple users are using the root value, procede with
1500 // simplification conservatively assuming that all elements
1501 // are needed.
1502 if (!V->hasOneUse()) {
1503 // Quit if we find multiple users of a non-root value though.
1504 // They'll be handled when it's their turn to be visited by
1505 // the main instcombine process.
1506 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001508 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001509
1510 // Conservatively assume that all elements are needed.
1511 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 }
1513
1514 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001515 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001516
1517 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001518 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001519 Value *TmpV;
1520 switch (I->getOpcode()) {
1521 default: break;
1522
1523 case Instruction::InsertElement: {
1524 // If this is a variable index, we don't know which element it overwrites.
1525 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001526 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001527 if (Idx == 0) {
1528 // Note that we can't propagate undef elt info, because we don't know
1529 // which elt is getting updated.
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1531 UndefElts2, Depth+1);
1532 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533 break;
1534 }
1535
1536 // If this is inserting an element that isn't demanded, remove this
1537 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001538 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001539 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1540 Worklist.Add(I);
1541 return I->getOperand(0);
1542 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001543
1544 // Otherwise, the element inserted overwrites whatever was there, so the
1545 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001546 APInt DemandedElts2 = DemandedElts;
1547 DemandedElts2.clear(IdxNo);
1548 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001549 UndefElts, Depth+1);
1550 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1551
1552 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001553 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001554 break;
1555 }
1556 case Instruction::ShuffleVector: {
1557 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001558 uint64_t LHSVWidth =
1559 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001560 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001561 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001562 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 unsigned MaskVal = Shuffle->getMaskValue(i);
1564 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001565 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001566 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001567 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001568 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 else
Evan Cheng388df622009-02-03 10:05:09 +00001570 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 }
1572 }
1573 }
1574
Nate Begeman7b254672009-02-11 22:36:25 +00001575 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001577 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1579
Nate Begeman7b254672009-02-11 22:36:25 +00001580 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1582 UndefElts3, Depth+1);
1583 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1584
1585 bool NewUndefElts = false;
1586 for (unsigned i = 0; i < VWidth; i++) {
1587 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001588 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001589 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001590 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001591 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001592 NewUndefElts = true;
1593 UndefElts.set(i);
1594 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001595 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001596 if (UndefElts3[MaskVal - LHSVWidth]) {
1597 NewUndefElts = true;
1598 UndefElts.set(i);
1599 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 }
1601 }
1602
1603 if (NewUndefElts) {
1604 // Add additional discovered undefs.
1605 std::vector<Constant*> Elts;
1606 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001607 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001608 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001609 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001610 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001611 Shuffle->getMaskValue(i)));
1612 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001613 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001614 MadeChange = true;
1615 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001616 break;
1617 }
Chris Lattner69878332007-04-14 22:29:23 +00001618 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001619 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001620 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1621 if (!VTy) break;
1622 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001623 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001624 unsigned Ratio;
1625
1626 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001627 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001628 // elements as are demanded of us.
1629 Ratio = 1;
1630 InputDemandedElts = DemandedElts;
1631 } else if (VWidth > InVWidth) {
1632 // Untested so far.
1633 break;
1634
1635 // If there are more elements in the result than there are in the source,
1636 // then an input element is live if any of the corresponding output
1637 // elements are live.
1638 Ratio = VWidth/InVWidth;
1639 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001640 if (DemandedElts[OutIdx])
1641 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001642 }
1643 } else {
1644 // Untested so far.
1645 break;
1646
1647 // If there are more elements in the source than there are in the result,
1648 // then an input element is live if the corresponding output element is
1649 // live.
1650 Ratio = InVWidth/VWidth;
1651 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001652 if (DemandedElts[InIdx/Ratio])
1653 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001654 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001655
Chris Lattner69878332007-04-14 22:29:23 +00001656 // div/rem demand all inputs, because they don't want divide by zero.
1657 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1658 UndefElts2, Depth+1);
1659 if (TmpV) {
1660 I->setOperand(0, TmpV);
1661 MadeChange = true;
1662 }
1663
1664 UndefElts = UndefElts2;
1665 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001666 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001667 // If there are more elements in the result than there are in the source,
1668 // then an output element is undef if the corresponding input element is
1669 // undef.
1670 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001671 if (UndefElts2[OutIdx/Ratio])
1672 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001673 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001674 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001675 // If there are more elements in the source than there are in the result,
1676 // then a result element is undef if all of the corresponding input
1677 // elements are undef.
1678 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1679 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001680 if (!UndefElts2[InIdx]) // Not undef?
1681 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001682 }
1683 break;
1684 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001685 case Instruction::And:
1686 case Instruction::Or:
1687 case Instruction::Xor:
1688 case Instruction::Add:
1689 case Instruction::Sub:
1690 case Instruction::Mul:
1691 // div/rem demand all inputs, because they don't want divide by zero.
1692 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1693 UndefElts, Depth+1);
1694 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1695 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1696 UndefElts2, Depth+1);
1697 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1698
1699 // Output elements are undefined if both are undefined. Consider things
1700 // like undef&0. The result is known zero, not undef.
1701 UndefElts &= UndefElts2;
1702 break;
1703
1704 case Instruction::Call: {
1705 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1706 if (!II) break;
1707 switch (II->getIntrinsicID()) {
1708 default: break;
1709
1710 // Binary vector operations that work column-wise. A dest element is a
1711 // function of the corresponding input elements from the two inputs.
1712 case Intrinsic::x86_sse_sub_ss:
1713 case Intrinsic::x86_sse_mul_ss:
1714 case Intrinsic::x86_sse_min_ss:
1715 case Intrinsic::x86_sse_max_ss:
1716 case Intrinsic::x86_sse2_sub_sd:
1717 case Intrinsic::x86_sse2_mul_sd:
1718 case Intrinsic::x86_sse2_min_sd:
1719 case Intrinsic::x86_sse2_max_sd:
1720 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1721 UndefElts, Depth+1);
1722 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1723 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1724 UndefElts2, Depth+1);
1725 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1726
1727 // If only the low elt is demanded and this is a scalarizable intrinsic,
1728 // scalarize it now.
1729 if (DemandedElts == 1) {
1730 switch (II->getIntrinsicID()) {
1731 default: break;
1732 case Intrinsic::x86_sse_sub_ss:
1733 case Intrinsic::x86_sse_mul_ss:
1734 case Intrinsic::x86_sse2_sub_sd:
1735 case Intrinsic::x86_sse2_mul_sd:
1736 // TODO: Lower MIN/MAX/ABS/etc
1737 Value *LHS = II->getOperand(1);
1738 Value *RHS = II->getOperand(2);
1739 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001740 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001741 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001742 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001743 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001744
1745 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001746 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001747 case Intrinsic::x86_sse_sub_ss:
1748 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001749 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001750 II->getName()), *II);
1751 break;
1752 case Intrinsic::x86_sse_mul_ss:
1753 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001754 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001755 II->getName()), *II);
1756 break;
1757 }
1758
1759 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001760 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001761 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001762 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001763 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001764 return New;
1765 }
1766 }
1767
1768 // Output elements are undefined if both are undefined. Consider things
1769 // like undef&0. The result is known zero, not undef.
1770 UndefElts &= UndefElts2;
1771 break;
1772 }
1773 break;
1774 }
1775 }
1776 return MadeChange ? I : 0;
1777}
1778
Dan Gohman45b4e482008-05-19 22:14:15 +00001779
Chris Lattner564a7272003-08-13 19:01:45 +00001780/// AssociativeOpt - Perform an optimization on an associative operator. This
1781/// function is designed to check a chain of associative operators for a
1782/// potential to apply a certain optimization. Since the optimization may be
1783/// applicable if the expression was reassociated, this checks the chain, then
1784/// reassociates the expression as necessary to expose the optimization
1785/// opportunity. This makes use of a special Functor, which must define
1786/// 'shouldApply' and 'apply' methods.
1787///
1788template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001789static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001790 unsigned Opcode = Root.getOpcode();
1791 Value *LHS = Root.getOperand(0);
1792
1793 // Quick check, see if the immediate LHS matches...
1794 if (F.shouldApply(LHS))
1795 return F.apply(Root);
1796
1797 // Otherwise, if the LHS is not of the same opcode as the root, return.
1798 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001799 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001800 // Should we apply this transform to the RHS?
1801 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1802
1803 // If not to the RHS, check to see if we should apply to the LHS...
1804 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1805 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1806 ShouldApply = true;
1807 }
1808
1809 // If the functor wants to apply the optimization to the RHS of LHSI,
1810 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1811 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001812 // Now all of the instructions are in the current basic block, go ahead
1813 // and perform the reassociation.
1814 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1815
1816 // First move the selected RHS to the LHS of the root...
1817 Root.setOperand(0, LHSI->getOperand(1));
1818
1819 // Make what used to be the LHS of the root be the user of the root...
1820 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001821 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001822 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001823 return 0;
1824 }
Chris Lattner65725312004-04-16 18:08:07 +00001825 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001826 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001827 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001828 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001829 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001830
1831 // Now propagate the ExtraOperand down the chain of instructions until we
1832 // get to LHSI.
1833 while (TmpLHSI != LHSI) {
1834 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001835 // Move the instruction to immediately before the chain we are
1836 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001837 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001838 ARI = NextLHSI;
1839
Chris Lattner564a7272003-08-13 19:01:45 +00001840 Value *NextOp = NextLHSI->getOperand(1);
1841 NextLHSI->setOperand(1, ExtraOperand);
1842 TmpLHSI = NextLHSI;
1843 ExtraOperand = NextOp;
1844 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001845
Chris Lattner564a7272003-08-13 19:01:45 +00001846 // Now that the instructions are reassociated, have the functor perform
1847 // the transformation...
1848 return F.apply(Root);
1849 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001850
Chris Lattner564a7272003-08-13 19:01:45 +00001851 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1852 }
1853 return 0;
1854}
1855
Dan Gohman844731a2008-05-13 00:00:25 +00001856namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001857
Nick Lewycky02d639f2008-05-23 04:34:58 +00001858// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001859struct AddRHS {
1860 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001861 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001862 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1863 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001864 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001865 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001866 }
1867};
1868
1869// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1870// iff C1&C2 == 0
1871struct AddMaskingAnd {
1872 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001873 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001874 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001875 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001876 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001877 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001878 }
1879 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001880 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001881 }
1882};
1883
Dan Gohman844731a2008-05-13 00:00:25 +00001884}
1885
Chris Lattner6e7ba452005-01-01 16:22:27 +00001886static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001887 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001888 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001889 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001890
Chris Lattner2eefe512004-04-09 19:05:30 +00001891 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001892 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1893 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001894
Chris Lattner2eefe512004-04-09 19:05:30 +00001895 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1896 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001897 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1898 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001899 }
1900
1901 Value *Op0 = SO, *Op1 = ConstOperand;
1902 if (!ConstIsRHS)
1903 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001904
Chris Lattner6e7ba452005-01-01 16:22:27 +00001905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001906 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1907 SO->getName()+".op");
1908 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1909 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1910 SO->getName()+".cmp");
1911 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1912 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1913 SO->getName()+".cmp");
1914 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001915}
1916
1917// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1918// constant as the other operand, try to fold the binary operator into the
1919// select arguments. This also works for Cast instructions, which obviously do
1920// not have a second operand.
1921static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1922 InstCombiner *IC) {
1923 // Don't modify shared select instructions
1924 if (!SI->hasOneUse()) return 0;
1925 Value *TV = SI->getOperand(1);
1926 Value *FV = SI->getOperand(2);
1927
1928 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001929 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001930 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001931
Chris Lattner6e7ba452005-01-01 16:22:27 +00001932 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1933 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1934
Gabor Greif051a9502008-04-06 20:25:17 +00001935 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1936 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001937 }
1938 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001939}
1940
Chris Lattner4e998b22004-09-29 05:07:12 +00001941
Chris Lattner5d1704d2009-09-27 19:57:57 +00001942/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1943/// has a PHI node as operand #0, see if we can fold the instruction into the
1944/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner4e998b22004-09-29 05:07:12 +00001945Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1946 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001947 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001948 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001949
Chris Lattner5d1704d2009-09-27 19:57:57 +00001950 // Check to see if all of the operands of the PHI are simple constants
1951 // (constantint/constantfp/undef). If there is one non-constant value,
1952 // remember the BB it is. If there is more than one or if *it* is a PHI, bail
1953 // out. We don't do arbitrary constant expressions here because moving their
1954 // computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001955 BasicBlock *NonConstBB = 0;
1956 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00001957 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1958 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001959 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001960 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001961 NonConstBB = PN->getIncomingBlock(i);
1962
1963 // If the incoming non-constant value is in I's block, we have an infinite
1964 // loop.
1965 if (NonConstBB == I.getParent())
1966 return 0;
1967 }
1968
1969 // If there is exactly one non-constant value, we can insert a copy of the
1970 // operation in that block. However, if this is a critical edge, we would be
1971 // inserting the computation one some other paths (e.g. inside a loop). Only
1972 // do this if the pred block is unconditionally branching into the phi block.
1973 if (NonConstBB) {
1974 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1975 if (!BI || !BI->isUnconditional()) return 0;
1976 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001977
1978 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001979 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001980 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001981 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001982 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001983
1984 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00001985 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
1986 // We only currently try to fold the condition of a select when it is a phi,
1987 // not the true/false values.
1988 for (unsigned i = 0; i != NumPHIValues; ++i) {
1989 Value *InV = 0;
1990 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1991 if (InC->isNullValue())
1992 InV = SI->getFalseValue();
1993 else
1994 InV = SI->getTrueValue();
1995 } else {
1996 assert(PN->getIncomingBlock(i) == NonConstBB);
1997 InV = SelectInst::Create(PN->getIncomingValue(i),
1998 SI->getTrueValue(), SI->getFalseValue(),
1999 "phitmp", NonConstBB->getTerminator());
2000 Worklist.Add(cast<Instruction>(InV));
2001 }
2002 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2003 }
2004 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002005 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002006 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002007 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002008 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002009 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002010 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002012 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 } else {
2014 assert(PN->getIncomingBlock(i) == NonConstBB);
2015 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002016 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 PN->getIncomingValue(i), C, "phitmp",
2018 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002019 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002020 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002021 CI->getPredicate(),
2022 PN->getIncomingValue(i), C, "phitmp",
2023 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002025 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002026
Chris Lattner7a1e9242009-08-30 06:13:40 +00002027 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 }
2029 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002030 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002031 } else {
2032 CastInst *CI = cast<CastInst>(&I);
2033 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002034 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002035 Value *InV;
2036 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002037 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002038 } else {
2039 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002041 I.getType(), "phitmp",
2042 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002043 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002044 }
2045 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002046 }
2047 }
2048 return ReplaceInstUsesWith(I, NewPN);
2049}
2050
Chris Lattner2454a2e2008-01-29 06:52:45 +00002051
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002052/// WillNotOverflowSignedAdd - Return true if we can prove that:
2053/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2054/// This basically requires proving that the add in the original type would not
2055/// overflow to change the sign bit or have a carry out.
2056bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2057 // There are different heuristics we can use for this. Here are some simple
2058 // ones.
2059
2060 // Add has the property that adding any two 2's complement numbers can only
2061 // have one carry bit which can change a sign. As such, if LHS and RHS each
2062 // have at least two sign bits, we know that the addition of the two values will
2063 // sign extend fine.
2064 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2065 return true;
2066
2067
2068 // If one of the operands only has one non-zero bit, and if the other operand
2069 // has a known-zero bit in a more significant place than it (not including the
2070 // sign bit) the ripple may go up to and fill the zero, but won't change the
2071 // sign. For example, (X & ~4) + 1.
2072
2073 // TODO: Implement.
2074
2075 return false;
2076}
2077
Chris Lattner2454a2e2008-01-29 06:52:45 +00002078
Chris Lattner7e708292002-06-25 16:13:24 +00002079Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002080 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002081 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002082
Chris Lattner66331a42004-04-10 22:01:55 +00002083 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002084 // X + undef -> undef
2085 if (isa<UndefValue>(RHS))
2086 return ReplaceInstUsesWith(I, RHS);
2087
Chris Lattner66331a42004-04-10 22:01:55 +00002088 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002089 if (RHSC->isNullValue())
2090 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002091
Chris Lattner66331a42004-04-10 22:01:55 +00002092 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002093 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002094 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002095 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002096 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002097 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002098
2099 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2100 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002101 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002102 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002103
Eli Friedman709b33d2009-07-13 22:27:52 +00002104 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002105 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002106 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002107 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002108 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002109
2110 if (isa<PHINode>(LHS))
2111 if (Instruction *NV = FoldOpIntoPhi(I))
2112 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002113
Chris Lattner4f637d42006-01-06 17:59:59 +00002114 ConstantInt *XorRHS = 0;
2115 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002116 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002117 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002118 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002119 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002120
Zhou Sheng4351c642007-04-02 08:20:41 +00002121 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002122 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002124 do {
2125 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002126 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002128 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002130 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002131 if (!MaskedValueIsZero(XorLHS,
2132 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002133 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002134 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002135 }
2136 }
2137 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002138 C0080Val = APIntOps::lshr(C0080Val, Size);
2139 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002141
Reid Spencer35c38852007-03-28 01:36:16 +00002142 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002143 // with funny bit widths then this switch statement should be removed. It
2144 // is just here to get the size of the "middle" type back up to something
2145 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002146 const Type *MiddleType = 0;
2147 switch (Size) {
2148 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002149 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2150 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2151 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002152 }
2153 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002154 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002155 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002156 }
2157 }
Chris Lattner66331a42004-04-10 22:01:55 +00002158 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002159
Owen Anderson1d0be152009-08-13 21:58:54 +00002160 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002161 return BinaryOperator::CreateXor(LHS, RHS);
2162
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002163 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002164 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002165 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002166 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002167
2168 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2169 if (RHSI->getOpcode() == Instruction::Sub)
2170 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2171 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2172 }
2173 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2174 if (LHSI->getOpcode() == Instruction::Sub)
2175 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2176 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2177 }
Robert Bocchino71698282004-07-27 21:02:21 +00002178 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002179
Chris Lattner5c4afb92002-05-08 22:46:53 +00002180 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002181 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002182 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002183 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002184 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002185 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002186 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002187 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002188 }
2189
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002190 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002191 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002192
2193 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002194 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002195 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002196 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002197
Misha Brukmanfd939082005-04-21 23:48:37 +00002198
Chris Lattner50af16a2004-11-13 19:50:12 +00002199 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002200 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002201 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002202 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002203
2204 // X*C1 + X*C2 --> X * (C1+C2)
2205 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002206 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002207 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002208 }
2209
2210 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002211 if (dyn_castFoldableMul(RHS, C2) == LHS)
2212 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002213
Chris Lattnere617c9e2007-01-05 02:17:46 +00002214 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002215 if (dyn_castNotVal(LHS) == RHS ||
2216 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002217 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002218
Chris Lattnerad3448c2003-02-18 19:57:07 +00002219
Chris Lattner564a7272003-08-13 19:01:45 +00002220 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002221 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2222 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002223 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002224
2225 // A+B --> A|B iff A and B have no bits set in common.
2226 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2227 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2228 APInt LHSKnownOne(IT->getBitWidth(), 0);
2229 APInt LHSKnownZero(IT->getBitWidth(), 0);
2230 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2231 if (LHSKnownZero != 0) {
2232 APInt RHSKnownOne(IT->getBitWidth(), 0);
2233 APInt RHSKnownZero(IT->getBitWidth(), 0);
2234 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2235
2236 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002237 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002238 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002239 }
2240 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002241
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002243 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002244 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002245 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2246 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002247 if (W != Y) {
2248 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002249 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002250 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002251 std::swap(W, X);
2252 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002253 std::swap(Y, Z);
2254 std::swap(W, X);
2255 }
2256 }
2257
2258 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002259 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002260 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002261 }
2262 }
2263 }
2264
Chris Lattner6b032052003-10-02 15:11:26 +00002265 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002266 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002267 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002268 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002269
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002270 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002271 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002272 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002273 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002274 if (Anded == CRHS) {
2275 // See if all bits from the first bit set in the Add RHS up are included
2276 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002277 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002278
2279 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002280 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002281
2282 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002283 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002284
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002285 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2286 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002287 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002288 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002289 }
2290 }
2291 }
2292
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002293 // Try to fold constant add into select arguments.
2294 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002295 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002296 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002297 }
2298
Chris Lattner42790482007-12-20 01:56:58 +00002299 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002300 {
2301 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002302 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002303 if (!SI) {
2304 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002305 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002306 }
Chris Lattner42790482007-12-20 01:56:58 +00002307 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002308 Value *TV = SI->getTrueValue();
2309 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002310 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002311
2312 // Can we fold the add into the argument of the select?
2313 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002314 if (match(FV, m_Zero()) &&
2315 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002316 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002317 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002318 if (match(TV, m_Zero()) &&
2319 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002320 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002321 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002322 }
2323 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002324
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002325 // Check for (add (sext x), y), see if we can merge this into an
2326 // integer add followed by a sext.
2327 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2328 // (add (sext x), cst) --> (sext (add x, cst'))
2329 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2330 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002331 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002332 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002333 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002334 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2335 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002336 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2337 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002338 return new SExtInst(NewAdd, I.getType());
2339 }
2340 }
2341
2342 // (add (sext x), (sext y)) --> (sext (add int x, y))
2343 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2344 // Only do this if x/y have the same type, if at last one of them has a
2345 // single use (so we don't increase the number of sexts), and if the
2346 // integer add will not overflow.
2347 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2348 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2349 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2350 RHSConv->getOperand(0))) {
2351 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002352 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2353 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002354 return new SExtInst(NewAdd, I.getType());
2355 }
2356 }
2357 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002358
2359 return Changed ? &I : 0;
2360}
2361
2362Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2363 bool Changed = SimplifyCommutative(I);
2364 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2365
2366 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2367 // X + 0 --> X
2368 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002369 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002370 (I.getType())->getValueAPF()))
2371 return ReplaceInstUsesWith(I, LHS);
2372 }
2373
2374 if (isa<PHINode>(LHS))
2375 if (Instruction *NV = FoldOpIntoPhi(I))
2376 return NV;
2377 }
2378
2379 // -A + B --> B - A
2380 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002381 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002382 return BinaryOperator::CreateFSub(RHS, LHSV);
2383
2384 // A + -B --> A - B
2385 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002386 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002387 return BinaryOperator::CreateFSub(LHS, V);
2388
2389 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2390 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2391 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2392 return ReplaceInstUsesWith(I, LHS);
2393
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002394 // Check for (add double (sitofp x), y), see if we can merge this into an
2395 // integer add followed by a promotion.
2396 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2397 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2398 // ... if the constant fits in the integer value. This is useful for things
2399 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2400 // requires a constant pool load, and generally allows the add to be better
2401 // instcombined.
2402 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2403 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002404 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002405 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002406 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002407 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2408 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002409 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2410 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002411 return new SIToFPInst(NewAdd, I.getType());
2412 }
2413 }
2414
2415 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2416 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2417 // Only do this if x/y have the same type, if at last one of them has a
2418 // single use (so we don't increase the number of int->fp conversions),
2419 // and if the integer add will not overflow.
2420 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2421 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2422 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2423 RHSConv->getOperand(0))) {
2424 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002425 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2426 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002427 return new SIToFPInst(NewAdd, I.getType());
2428 }
2429 }
2430 }
2431
Chris Lattner7e708292002-06-25 16:13:24 +00002432 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002433}
2434
Chris Lattner7e708292002-06-25 16:13:24 +00002435Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002436 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002437
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002438 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002440
Chris Lattner233f7dc2002-08-12 21:17:25 +00002441 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002442 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002444
Chris Lattnere87597f2004-10-16 18:11:37 +00002445 if (isa<UndefValue>(Op0))
2446 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2447 if (isa<UndefValue>(Op1))
2448 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2449
Chris Lattnerd65460f2003-11-05 01:06:05 +00002450 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2451 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002452 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002453 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002454
Chris Lattnerd65460f2003-11-05 01:06:05 +00002455 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002456 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002457 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002458 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002459
Chris Lattner76b7a062007-01-15 07:02:54 +00002460 // -(X >>u 31) -> (X >>s 31)
2461 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002462 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002463 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002464 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002465 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002466 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002467 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002468 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002469 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002470 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002471 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002472 }
2473 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002474 }
2475 else if (SI->getOpcode() == Instruction::AShr) {
2476 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2477 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002478 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002479 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002480 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002481 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002482 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002483 }
2484 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002485 }
2486 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002487 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002488
2489 // Try to fold constant sub into select arguments.
2490 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002491 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002492 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002493
2494 // C - zext(bool) -> bool ? C - 1 : C
2495 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002496 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002497 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002498 }
2499
Owen Anderson1d0be152009-08-13 21:58:54 +00002500 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002501 return BinaryOperator::CreateXor(Op0, Op1);
2502
Chris Lattner43d84d62005-04-07 16:15:25 +00002503 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002504 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002505 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002506 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002507 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002508 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002509 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002510 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002511 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2512 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2513 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002514 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002515 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002516 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002517 }
2518
Chris Lattnerfd059242003-10-15 16:48:29 +00002519 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002520 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2521 // is not used by anyone else...
2522 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002523 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002524 // Swap the two operands of the subexpr...
2525 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2526 Op1I->setOperand(0, IIOp1);
2527 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002528
Chris Lattnera2881962003-02-18 19:28:33 +00002529 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002531 }
2532
2533 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2534 //
2535 if (Op1I->getOpcode() == Instruction::And &&
2536 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2537 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2538
Chris Lattner74381062009-08-30 07:44:24 +00002539 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002540 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002541 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002542
Reid Spencerac5209e2006-10-16 23:08:08 +00002543 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002544 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002545 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002546 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002547 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002548 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002549 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002550
Chris Lattnerad3448c2003-02-18 19:57:07 +00002551 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002552 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002553 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002554 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002555 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002556 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002557 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002558 }
Chris Lattner40371712002-05-09 01:29:19 +00002559 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002560 }
Chris Lattnera2881962003-02-18 19:28:33 +00002561
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002562 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2563 if (Op0I->getOpcode() == Instruction::Add) {
2564 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2565 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2566 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2567 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2568 } else if (Op0I->getOpcode() == Instruction::Sub) {
2569 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002570 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002571 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002572 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002573 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002574
Chris Lattner50af16a2004-11-13 19:50:12 +00002575 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002576 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002577 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002578 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002579
Chris Lattner50af16a2004-11-13 19:50:12 +00002580 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002581 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002582 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002583 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002584 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002585}
2586
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002587Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2588 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2589
2590 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002591 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 return BinaryOperator::CreateFAdd(Op0, V);
2593
2594 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2595 if (Op1I->getOpcode() == Instruction::FAdd) {
2596 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002597 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002598 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002599 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002600 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002601 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002602 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002603 }
2604
2605 return 0;
2606}
2607
Chris Lattnera0141b92007-07-15 20:42:37 +00002608/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2609/// comparison only checks the sign bit. If it only checks the sign bit, set
2610/// TrueIfSigned if the result of the comparison is true when the input value is
2611/// signed.
2612static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2613 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002614 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002615 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2616 TrueIfSigned = true;
2617 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002618 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2619 TrueIfSigned = true;
2620 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002621 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2622 TrueIfSigned = false;
2623 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002624 case ICmpInst::ICMP_UGT:
2625 // True if LHS u> RHS and RHS == high-bit-mask - 1
2626 TrueIfSigned = true;
2627 return RHS->getValue() ==
2628 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2629 case ICmpInst::ICMP_UGE:
2630 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2631 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002632 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002633 default:
2634 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002635 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002636}
2637
Chris Lattner7e708292002-06-25 16:13:24 +00002638Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002639 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002640 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002641
Eli Friedman1694e092009-07-18 09:12:15 +00002642 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002643 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002644
Chris Lattner233f7dc2002-08-12 21:17:25 +00002645 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002646 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2647 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002648
2649 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002650 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002651 if (SI->getOpcode() == Instruction::Shl)
2652 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002653 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002654 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002655
Zhou Sheng843f07672007-04-19 05:39:12 +00002656 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002657 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2658 if (CI->equalsInt(1)) // X * 1 == X
2659 return ReplaceInstUsesWith(I, Op0);
2660 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002661 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002662
Zhou Sheng97b52c22007-03-29 01:57:21 +00002663 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002664 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002665 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002666 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002667 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002668 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002669 if (Op1->isNullValue())
2670 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002671
2672 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2673 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002674 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002675
2676 // As above, vector X*splat(1.0) -> X in all defined cases.
2677 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002678 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2679 if (CI->equalsInt(1))
2680 return ReplaceInstUsesWith(I, Op0);
2681 }
2682 }
Chris Lattnera2881962003-02-18 19:28:33 +00002683 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002684
2685 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2686 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002687 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002688 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002689 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2690 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002691 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002692
2693 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002694
2695 // Try to fold constant mul into select arguments.
2696 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002697 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002698 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002699
2700 if (isa<PHINode>(Op0))
2701 if (Instruction *NV = FoldOpIntoPhi(I))
2702 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002703 }
2704
Dan Gohman186a6362009-08-12 16:04:34 +00002705 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2706 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002707 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002708
Nick Lewycky0c730792008-11-21 07:33:58 +00002709 // (X / Y) * Y = X - (X % Y)
2710 // (X / Y) * -Y = (X % Y) - X
2711 {
2712 Value *Op1 = I.getOperand(1);
2713 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2714 if (!BO ||
2715 (BO->getOpcode() != Instruction::UDiv &&
2716 BO->getOpcode() != Instruction::SDiv)) {
2717 Op1 = Op0;
2718 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2719 }
Dan Gohman186a6362009-08-12 16:04:34 +00002720 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002721 if (BO && BO->hasOneUse() &&
2722 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2723 (BO->getOpcode() == Instruction::UDiv ||
2724 BO->getOpcode() == Instruction::SDiv)) {
2725 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2726
Dan Gohmanfa94b942009-08-12 16:33:09 +00002727 // If the division is exact, X % Y is zero.
2728 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2729 if (SDiv->isExact()) {
2730 if (Op1BO == Op1)
2731 return ReplaceInstUsesWith(I, Op0BO);
2732 else
2733 return BinaryOperator::CreateNeg(Op0BO);
2734 }
2735
Chris Lattner74381062009-08-30 07:44:24 +00002736 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002737 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002738 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002739 else
Chris Lattner74381062009-08-30 07:44:24 +00002740 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002741 Rem->takeName(BO);
2742
2743 if (Op1BO == Op1)
2744 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002745 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002746 }
2747 }
2748
Owen Anderson1d0be152009-08-13 21:58:54 +00002749 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002750 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2751
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002752 // If one of the operands of the multiply is a cast from a boolean value, then
2753 // we know the bool is either zero or one, so this is a 'masking' multiply.
2754 // See if we can simplify things based on how the boolean was originally
2755 // formed.
2756 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002757 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002758 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002759 BoolCast = CI;
2760 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002761 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002762 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002763 BoolCast = CI;
2764 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002765 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002766 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2767 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002768 bool TIS = false;
2769
Reid Spencere4d87aa2006-12-23 06:05:41 +00002770 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002771 // multiply into a shift/and combination.
2772 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002773 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2774 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002775 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002776 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002777 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002778 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2779 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002780
2781 // If the multiply type is not the same as the source type, sign extend
2782 // or truncate to the multiply type.
Chris Lattner2345d1d2009-08-30 20:01:10 +00002783 if (I.getType() != V->getType())
2784 V = Builder->CreateIntCast(V, I.getType(), true);
Misha Brukmanfd939082005-04-21 23:48:37 +00002785
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002786 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002787 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002788 }
2789 }
2790 }
2791
Chris Lattner7e708292002-06-25 16:13:24 +00002792 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002793}
2794
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002795Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2796 bool Changed = SimplifyCommutative(I);
2797 Value *Op0 = I.getOperand(0);
2798
2799 // Simplify mul instructions with a constant RHS...
2800 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2801 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2802 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2803 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2804 if (Op1F->isExactlyValue(1.0))
2805 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2806 } else if (isa<VectorType>(Op1->getType())) {
2807 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2808 // As above, vector X*splat(1.0) -> X in all defined cases.
2809 if (Constant *Splat = Op1V->getSplatValue()) {
2810 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2811 if (F->isExactlyValue(1.0))
2812 return ReplaceInstUsesWith(I, Op0);
2813 }
2814 }
2815 }
2816
2817 // Try to fold constant mul into select arguments.
2818 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2819 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2820 return R;
2821
2822 if (isa<PHINode>(Op0))
2823 if (Instruction *NV = FoldOpIntoPhi(I))
2824 return NV;
2825 }
2826
Dan Gohman186a6362009-08-12 16:04:34 +00002827 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2828 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002829 return BinaryOperator::CreateFMul(Op0v, Op1v);
2830
2831 return Changed ? &I : 0;
2832}
2833
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002834/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2835/// instruction.
2836bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2837 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2838
2839 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2840 int NonNullOperand = -1;
2841 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2842 if (ST->isNullValue())
2843 NonNullOperand = 2;
2844 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2845 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2846 if (ST->isNullValue())
2847 NonNullOperand = 1;
2848
2849 if (NonNullOperand == -1)
2850 return false;
2851
2852 Value *SelectCond = SI->getOperand(0);
2853
2854 // Change the div/rem to use 'Y' instead of the select.
2855 I.setOperand(1, SI->getOperand(NonNullOperand));
2856
2857 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2858 // problem. However, the select, or the condition of the select may have
2859 // multiple uses. Based on our knowledge that the operand must be non-zero,
2860 // propagate the known value for the select into other uses of it, and
2861 // propagate a known value of the condition into its other users.
2862
2863 // If the select and condition only have a single use, don't bother with this,
2864 // early exit.
2865 if (SI->use_empty() && SelectCond->hasOneUse())
2866 return true;
2867
2868 // Scan the current block backward, looking for other uses of SI.
2869 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2870
2871 while (BBI != BBFront) {
2872 --BBI;
2873 // If we found a call to a function, we can't assume it will return, so
2874 // information from below it cannot be propagated above it.
2875 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2876 break;
2877
2878 // Replace uses of the select or its condition with the known values.
2879 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2880 I != E; ++I) {
2881 if (*I == SI) {
2882 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002883 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002884 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002885 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2886 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002887 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002888 }
2889 }
2890
2891 // If we past the instruction, quit looking for it.
2892 if (&*BBI == SI)
2893 SI = 0;
2894 if (&*BBI == SelectCond)
2895 SelectCond = 0;
2896
2897 // If we ran out of things to eliminate, break out of the loop.
2898 if (SelectCond == 0 && SI == 0)
2899 break;
2900
2901 }
2902 return true;
2903}
2904
2905
Reid Spencer1628cec2006-10-26 06:15:43 +00002906/// This function implements the transforms on div instructions that work
2907/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2908/// used by the visitors to those instructions.
2909/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002910Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002911 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002912
Chris Lattner50b2ca42008-02-19 06:12:18 +00002913 // undef / X -> 0 for integer.
2914 // undef / X -> undef for FP (the undef could be a snan).
2915 if (isa<UndefValue>(Op0)) {
2916 if (Op0->getType()->isFPOrFPVector())
2917 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002918 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002919 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002920
2921 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002922 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002923 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002924
Reid Spencer1628cec2006-10-26 06:15:43 +00002925 return 0;
2926}
Misha Brukmanfd939082005-04-21 23:48:37 +00002927
Reid Spencer1628cec2006-10-26 06:15:43 +00002928/// This function implements the transforms common to both integer division
2929/// instructions (udiv and sdiv). It is called by the visitors to those integer
2930/// division instructions.
2931/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002932Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002933 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2934
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002935 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002936 if (Op0 == Op1) {
2937 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002938 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002939 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002940 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002941 }
2942
Owen Andersoneed707b2009-07-24 23:12:02 +00002943 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002944 return ReplaceInstUsesWith(I, CI);
2945 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002946
Reid Spencer1628cec2006-10-26 06:15:43 +00002947 if (Instruction *Common = commonDivTransforms(I))
2948 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002949
2950 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2951 // This does not apply for fdiv.
2952 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2953 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002954
2955 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2956 // div X, 1 == X
2957 if (RHS->equalsInt(1))
2958 return ReplaceInstUsesWith(I, Op0);
2959
2960 // (X / C1) / C2 -> X / (C1*C2)
2961 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2962 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2963 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002964 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002965 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002967 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002968 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002969 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002970 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002971
Reid Spencerbca0e382007-03-23 20:05:17 +00002972 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002973 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2974 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2975 return R;
2976 if (isa<PHINode>(Op0))
2977 if (Instruction *NV = FoldOpIntoPhi(I))
2978 return NV;
2979 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002980 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002981
Chris Lattnera2881962003-02-18 19:28:33 +00002982 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002983 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002984 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002985 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002986
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002987 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002988 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002989 return ReplaceInstUsesWith(I, Op0);
2990
Nick Lewycky895f0852008-11-27 20:21:08 +00002991 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2992 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2993 // div X, 1 == X
2994 if (X->isOne())
2995 return ReplaceInstUsesWith(I, Op0);
2996 }
2997
Reid Spencer1628cec2006-10-26 06:15:43 +00002998 return 0;
2999}
3000
3001Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3002 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3003
3004 // Handle the integer div common cases
3005 if (Instruction *Common = commonIDivTransforms(I))
3006 return Common;
3007
Reid Spencer1628cec2006-10-26 06:15:43 +00003008 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003009 // X udiv C^2 -> X >> C
3010 // Check to see if this is an unsigned division with an exact power of 2,
3011 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003012 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003013 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003014 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003015
3016 // X udiv C, where C >= signbit
3017 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003018 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003019 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003020 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003021 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003022 }
3023
3024 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003025 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 if (RHSI->getOpcode() == Instruction::Shl &&
3027 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003028 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003029 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003030 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003031 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003032 if (uint32_t C2 = C1.logBase2())
3033 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003035 }
3036 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003037 }
3038
Reid Spencer1628cec2006-10-26 06:15:43 +00003039 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003042 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003044 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003045 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003047 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003048 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003049 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003050 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003051
3052 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003053 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003054 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003055
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003056 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003057 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003058 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003059 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003060 return 0;
3061}
3062
Reid Spencer1628cec2006-10-26 06:15:43 +00003063Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3064 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3065
3066 // Handle the integer div common cases
3067 if (Instruction *Common = commonIDivTransforms(I))
3068 return Common;
3069
3070 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3071 // sdiv X, -1 == -X
3072 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003073 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003074
Dan Gohmanfa94b942009-08-12 16:33:09 +00003075 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003076 if (cast<SDivOperator>(&I)->isExact() &&
3077 RHS->getValue().isNonNegative() &&
3078 RHS->getValue().isPowerOf2()) {
3079 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3080 RHS->getValue().exactLogBase2());
3081 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3082 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003083
3084 // -X/C --> X/-C provided the negation doesn't overflow.
3085 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3086 if (isa<Constant>(Sub->getOperand(0)) &&
3087 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003088 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003089 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3090 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003091 }
3092
3093 // If the sign bits of both operands are zero (i.e. we can prove they are
3094 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003095 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003096 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003097 if (MaskedValueIsZero(Op0, Mask)) {
3098 if (MaskedValueIsZero(Op1, Mask)) {
3099 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3100 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3101 }
3102 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003103 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003104 ShiftedInt->getValue().isPowerOf2()) {
3105 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3106 // Safe because the only negative value (1 << Y) can take on is
3107 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3108 // the sign bit set.
3109 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3110 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003111 }
Eli Friedman8be17392009-07-18 09:53:21 +00003112 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003113
3114 return 0;
3115}
3116
3117Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3118 return commonDivTransforms(I);
3119}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003120
Reid Spencer0a783f72006-11-02 01:53:59 +00003121/// This function implements the transforms on rem instructions that work
3122/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3123/// is used by the visitors to those instructions.
3124/// @brief Transforms common to all three rem instructions
3125Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003126 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003127
Chris Lattner50b2ca42008-02-19 06:12:18 +00003128 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3129 if (I.getType()->isFPOrFPVector())
3130 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003131 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003132 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003133 if (isa<UndefValue>(Op1))
3134 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003135
3136 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003137 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3138 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003139
Reid Spencer0a783f72006-11-02 01:53:59 +00003140 return 0;
3141}
3142
3143/// This function implements the transforms common to both integer remainder
3144/// instructions (urem and srem). It is called by the visitors to those integer
3145/// remainder instructions.
3146/// @brief Common integer remainder transforms
3147Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3148 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3149
3150 if (Instruction *common = commonRemTransforms(I))
3151 return common;
3152
Dale Johannesened6af242009-01-21 00:35:19 +00003153 // 0 % X == 0 for integer, we don't need to preserve faults!
3154 if (Constant *LHS = dyn_cast<Constant>(Op0))
3155 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003156 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003157
Chris Lattner857e8cd2004-12-12 21:48:58 +00003158 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003159 // X % 0 == undef, we don't need to preserve faults!
3160 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003161 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003162
Chris Lattnera2881962003-02-18 19:28:33 +00003163 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003164 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003165
Chris Lattner97943922006-02-28 05:49:21 +00003166 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3168 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3169 return R;
3170 } else if (isa<PHINode>(Op0I)) {
3171 if (Instruction *NV = FoldOpIntoPhi(I))
3172 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003173 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003174
3175 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003176 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003177 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003178 }
Chris Lattnera2881962003-02-18 19:28:33 +00003179 }
3180
Reid Spencer0a783f72006-11-02 01:53:59 +00003181 return 0;
3182}
3183
3184Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3185 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3186
3187 if (Instruction *common = commonIRemTransforms(I))
3188 return common;
3189
3190 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3191 // X urem C^2 -> X and C
3192 // Check to see if this is an unsigned remainder with an exact power of 2,
3193 // if so, convert to a bitwise and.
3194 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003195 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003196 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003197 }
3198
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003199 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003200 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3201 if (RHSI->getOpcode() == Instruction::Shl &&
3202 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003203 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003204 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003205 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003206 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003207 }
3208 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003209 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003210
Reid Spencer0a783f72006-11-02 01:53:59 +00003211 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3212 // where C1&C2 are powers of two.
3213 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3214 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3215 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3216 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003217 if ((STO->getValue().isPowerOf2()) &&
3218 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003219 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3220 SI->getName()+".t");
3221 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3222 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003223 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003224 }
3225 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003226 }
3227
Chris Lattner3f5b8772002-05-06 16:14:14 +00003228 return 0;
3229}
3230
Reid Spencer0a783f72006-11-02 01:53:59 +00003231Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3232 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3233
Dan Gohmancff55092007-11-05 23:16:33 +00003234 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003235 if (Instruction *Common = commonIRemTransforms(I))
3236 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003237
Dan Gohman186a6362009-08-12 16:04:34 +00003238 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003239 if (!isa<Constant>(RHSNeg) ||
3240 (isa<ConstantInt>(RHSNeg) &&
3241 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003243 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 I.setOperand(1, RHSNeg);
3245 return &I;
3246 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003247
Dan Gohmancff55092007-11-05 23:16:33 +00003248 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003249 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003250 if (I.getType()->isInteger()) {
3251 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3252 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3253 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003254 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003255 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003256 }
3257
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003258 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003259 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3260 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003261
Nick Lewycky9dce8732008-12-20 16:48:00 +00003262 bool hasNegative = false;
3263 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3264 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3265 if (RHS->getValue().isNegative())
3266 hasNegative = true;
3267
3268 if (hasNegative) {
3269 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270 for (unsigned i = 0; i != VWidth; ++i) {
3271 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3272 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003273 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003274 else
3275 Elts[i] = RHS;
3276 }
3277 }
3278
Owen Andersonaf7ec972009-07-28 21:19:26 +00003279 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003280 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003281 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003282 I.setOperand(1, NewRHSV);
3283 return &I;
3284 }
3285 }
3286 }
3287
Reid Spencer0a783f72006-11-02 01:53:59 +00003288 return 0;
3289}
3290
3291Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003292 return commonRemTransforms(I);
3293}
3294
Chris Lattner457dd822004-06-09 07:59:58 +00003295// isOneBitSet - Return true if there is exactly one bit set in the specified
3296// constant.
3297static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003298 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003299}
3300
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003301// isHighOnes - Return true if the constant is of the form 1+0+.
3302// This is the same as lowones(~X).
3303static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003304 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003305}
3306
Reid Spencere4d87aa2006-12-23 06:05:41 +00003307/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003308/// are carefully arranged to allow folding of expressions such as:
3309///
3310/// (A < B) | (A > B) --> (A != B)
3311///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003312/// Note that this is only valid if the first and second predicates have the
3313/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003314///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003315/// Three bits are used to represent the condition, as follows:
3316/// 0 A > B
3317/// 1 A == B
3318/// 2 A < B
3319///
3320/// <=> Value Definition
3321/// 000 0 Always false
3322/// 001 1 A > B
3323/// 010 2 A == B
3324/// 011 3 A >= B
3325/// 100 4 A < B
3326/// 101 5 A != B
3327/// 110 6 A <= B
3328/// 111 7 Always true
3329///
3330static unsigned getICmpCode(const ICmpInst *ICI) {
3331 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003332 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333 case ICmpInst::ICMP_UGT: return 1; // 001
3334 case ICmpInst::ICMP_SGT: return 1; // 001
3335 case ICmpInst::ICMP_EQ: return 2; // 010
3336 case ICmpInst::ICMP_UGE: return 3; // 011
3337 case ICmpInst::ICMP_SGE: return 3; // 011
3338 case ICmpInst::ICMP_ULT: return 4; // 100
3339 case ICmpInst::ICMP_SLT: return 4; // 100
3340 case ICmpInst::ICMP_NE: return 5; // 101
3341 case ICmpInst::ICMP_ULE: return 6; // 110
3342 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003343 // True -> 7
3344 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003345 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003346 return 0;
3347 }
3348}
3349
Evan Cheng8db90722008-10-14 17:15:11 +00003350/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3351/// predicate into a three bit mask. It also returns whether it is an ordered
3352/// predicate by reference.
3353static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3354 isOrdered = false;
3355 switch (CC) {
3356 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3357 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003358 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3359 case FCmpInst::FCMP_UGT: return 1; // 001
3360 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3361 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003362 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3363 case FCmpInst::FCMP_UGE: return 3; // 011
3364 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3365 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003366 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3367 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003368 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3369 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003370 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003371 default:
3372 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003373 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003374 return 0;
3375 }
3376}
3377
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378/// getICmpValue - This is the complement of getICmpCode, which turns an
3379/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003380/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003381/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003382static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003383 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003385 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003386 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387 case 1:
3388 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003389 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003391 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3392 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 case 3:
3394 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003395 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003397 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003398 case 4:
3399 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003400 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003401 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003402 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3403 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003404 case 6:
3405 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003406 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003407 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003408 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003409 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003410 }
3411}
3412
Evan Cheng8db90722008-10-14 17:15:11 +00003413/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3414/// opcode and two operands into either a FCmp instruction. isordered is passed
3415/// in to determine which kind of predicate to use in the new fcmp instruction.
3416static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003417 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003418 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003419 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003420 case 0:
3421 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003422 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003423 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003424 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 case 1:
3426 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003430 case 2:
3431 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003432 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003433 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003434 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 case 3:
3436 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003437 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003438 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003439 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003440 case 4:
3441 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003442 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003443 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003444 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003445 case 5:
3446 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003447 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003448 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003450 case 6:
3451 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003452 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003454 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003455 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003456 }
3457}
3458
Chris Lattnerb9553d62008-11-16 04:55:20 +00003459/// PredicatesFoldable - Return true if both predicates match sign or if at
3460/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003461static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3462 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003463 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3464 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465}
3466
3467namespace {
3468// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3469struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003470 InstCombiner &IC;
3471 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003472 ICmpInst::Predicate pred;
3473 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3474 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3475 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003476 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003477 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3478 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003479 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3480 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481 return false;
3482 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483 Instruction *apply(Instruction &Log) const {
3484 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3485 if (ICI->getOperand(0) != LHS) {
3486 assert(ICI->getOperand(1) == LHS);
3487 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 }
3489
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003490 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003491 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003492 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003493 unsigned Code;
3494 switch (Log.getOpcode()) {
3495 case Instruction::And: Code = LHSCode & RHSCode; break;
3496 case Instruction::Or: Code = LHSCode | RHSCode; break;
3497 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003498 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003499 }
3500
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003501 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3502 ICmpInst::isSignedPredicate(ICI->getPredicate());
3503
Owen Andersond672ecb2009-07-03 00:17:18 +00003504 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003505 if (Instruction *I = dyn_cast<Instruction>(RV))
3506 return I;
3507 // Otherwise, it's a constant boolean value...
3508 return IC.ReplaceInstUsesWith(Log, RV);
3509 }
3510};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003511} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003512
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003513// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3514// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003515// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003517 ConstantInt *OpRHS,
3518 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 BinaryOperator &TheAnd) {
3520 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003521 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003522 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003523 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003524
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003525 switch (Op->getOpcode()) {
3526 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003527 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003528 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003529 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003530 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003531 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003532 }
3533 break;
3534 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003535 if (Together == AndRHS) // (X | C) & C --> C
3536 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003537
Chris Lattner6e7ba452005-01-01 16:22:27 +00003538 if (Op->hasOneUse() && Together != OpRHS) {
3539 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003540 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003541 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003542 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 }
3544 break;
3545 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003546 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547 // Adding a one to a single bit bit-field should be turned into an XOR
3548 // of the bit. First thing to check is to see if this AND is with a
3549 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003550 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551
3552 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003553 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003554 // Ok, at this point, we know that we are masking the result of the
3555 // ADD down to exactly one bit. If the constant we are adding has
3556 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003557 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003558
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 // Check to see if any bits below the one bit set in AndRHSV are set.
3560 if ((AddRHS & (AndRHSV-1)) == 0) {
3561 // If not, the only thing that can effect the output of the AND is
3562 // the bit specified by AndRHSV. If that bit is set, the effect of
3563 // the XOR is to toggle the bit. If it is clear, then the ADD has
3564 // no effect.
3565 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3566 TheAnd.setOperand(0, X);
3567 return &TheAnd;
3568 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003570 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003571 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003572 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003573 }
3574 }
3575 }
3576 }
3577 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003578
3579 case Instruction::Shl: {
3580 // We know that the AND will not produce any of the bits shifted in, so if
3581 // the anded constant includes them, clear them now!
3582 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003583 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003584 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003585 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003586 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003587
Zhou Sheng290bec52007-03-29 08:15:12 +00003588 if (CI->getValue() == ShlMask) {
3589 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003590 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3591 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003592 TheAnd.setOperand(1, CI);
3593 return &TheAnd;
3594 }
3595 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003596 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003597 case Instruction::LShr:
3598 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003599 // We know that the AND will not produce any of the bits shifted in, so if
3600 // the anded constant includes them, clear them now! This only applies to
3601 // unsigned shifts, because a signed shr may bring in set bits!
3602 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003603 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003604 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003605 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003606 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003607
Zhou Sheng290bec52007-03-29 08:15:12 +00003608 if (CI->getValue() == ShrMask) {
3609 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003610 return ReplaceInstUsesWith(TheAnd, Op);
3611 } else if (CI != AndRHS) {
3612 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3613 return &TheAnd;
3614 }
3615 break;
3616 }
3617 case Instruction::AShr:
3618 // Signed shr.
3619 // See if this is shifting in some sign extension, then masking it out
3620 // with an and.
3621 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003622 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003623 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003624 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003625 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003626 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003627 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003628 // Make the argument unsigned.
3629 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003630 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003631 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003632 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003633 }
3634 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003635 }
3636 return 0;
3637}
3638
Chris Lattner8b170942002-08-09 23:47:40 +00003639
Chris Lattnera96879a2004-09-29 17:40:11 +00003640/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3641/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3643/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003644/// insert new instructions.
3645Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646 bool isSigned, bool Inside,
3647 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003648 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003649 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003650 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651
Chris Lattnera96879a2004-09-29 17:40:11 +00003652 if (Inside) {
3653 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003654 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003655
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003657 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003658 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003659 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003660 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 }
3662
3663 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003664 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003665 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003666 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003667 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003668 }
3669
3670 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003671 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003672
Reid Spencere4e40032007-03-21 23:19:50 +00003673 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003674 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003675 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 ICmpInst::Predicate pred = (isSigned ?
3677 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003678 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003680
Reid Spencere4e40032007-03-21 23:19:50 +00003681 // Emit V-Lo >u Hi-1-Lo
3682 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003683 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003684 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003685 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003686 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003687}
3688
Chris Lattner7203e152005-09-18 07:22:02 +00003689// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3690// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3691// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3692// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003693static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003694 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003695 uint32_t BitWidth = Val->getType()->getBitWidth();
3696 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003697
3698 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003699 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003700 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003701 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003702 return true;
3703}
3704
Chris Lattner7203e152005-09-18 07:22:02 +00003705/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3706/// where isSub determines whether the operator is a sub. If we can fold one of
3707/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003708///
3709/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3710/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3711/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3712///
3713/// return (A +/- B).
3714///
3715Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003716 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003717 Instruction &I) {
3718 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3719 if (!LHSI || LHSI->getNumOperands() != 2 ||
3720 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3721
3722 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3723
3724 switch (LHSI->getOpcode()) {
3725 default: return 0;
3726 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003727 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003728 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003729 if ((Mask->getValue().countLeadingZeros() +
3730 Mask->getValue().countPopulation()) ==
3731 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003732 break;
3733
3734 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3735 // part, we don't need any explicit masks to take them out of A. If that
3736 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003737 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003738 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003739 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003740 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003741 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003742 break;
3743 }
3744 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003745 return 0;
3746 case Instruction::Or:
3747 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003748 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003749 if ((Mask->getValue().countLeadingZeros() +
3750 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003751 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003752 break;
3753 return 0;
3754 }
3755
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003757 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3758 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003759}
3760
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003761/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3762Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3763 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003764 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003765 ConstantInt *LHSCst, *RHSCst;
3766 ICmpInst::Predicate LHSCC, RHSCC;
3767
Chris Lattnerea065fb2008-11-16 05:10:52 +00003768 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003769 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003770 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003771 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003772 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003773 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003774
3775 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3776 // where C is a power of 2
3777 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3778 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003779 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003780 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003781 }
3782
3783 // From here on, we only handle:
3784 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3785 if (Val != Val2) return 0;
3786
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003787 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3788 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3789 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3790 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3791 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3792 return 0;
3793
3794 // We can't fold (ugt x, C) & (sgt x, C2).
3795 if (!PredicatesFoldable(LHSCC, RHSCC))
3796 return 0;
3797
3798 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003799 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003800 if (ICmpInst::isSignedPredicate(LHSCC) ||
3801 (ICmpInst::isEquality(LHSCC) &&
3802 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003803 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003804 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003805 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3806
3807 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003808 std::swap(LHS, RHS);
3809 std::swap(LHSCst, RHSCst);
3810 std::swap(LHSCC, RHSCC);
3811 }
3812
3813 // At this point, we know we have have two icmp instructions
3814 // comparing a value against two constants and and'ing the result
3815 // together. Because of the above check, we know that we only have
3816 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3817 // (from the FoldICmpLogical check above), that the two constants
3818 // are not equal and that the larger constant is on the RHS
3819 assert(LHSCst != RHSCst && "Compares not folded above?");
3820
3821 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003822 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 case ICmpInst::ICMP_EQ:
3824 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003825 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003826 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3827 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3828 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003829 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003830 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3831 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3832 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3833 return ReplaceInstUsesWith(I, LHS);
3834 }
3835 case ICmpInst::ICMP_NE:
3836 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003837 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003838 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003839 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003840 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 break; // (X != 13 & X u< 15) -> no change
3842 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003843 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003844 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003845 break; // (X != 13 & X s< 15) -> no change
3846 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3847 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3848 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3849 return ReplaceInstUsesWith(I, RHS);
3850 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003851 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003852 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003853 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003854 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003855 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003856 }
3857 break; // (X != 13 & X != 15) -> no change
3858 }
3859 break;
3860 case ICmpInst::ICMP_ULT:
3861 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003862 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003863 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3864 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003865 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3867 break;
3868 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3869 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3870 return ReplaceInstUsesWith(I, LHS);
3871 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3872 break;
3873 }
3874 break;
3875 case ICmpInst::ICMP_SLT:
3876 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003877 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3879 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003880 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3882 break;
3883 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3884 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3885 return ReplaceInstUsesWith(I, LHS);
3886 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3887 break;
3888 }
3889 break;
3890 case ICmpInst::ICMP_UGT:
3891 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003892 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003893 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3894 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3895 return ReplaceInstUsesWith(I, RHS);
3896 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3897 break;
3898 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003899 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003900 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003902 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003903 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003904 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003905 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3906 break;
3907 }
3908 break;
3909 case ICmpInst::ICMP_SGT:
3910 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003911 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003912 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3913 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3914 return ReplaceInstUsesWith(I, RHS);
3915 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3916 break;
3917 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003918 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003919 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003920 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003921 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003922 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003923 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003924 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3925 break;
3926 }
3927 break;
3928 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003929
3930 return 0;
3931}
3932
Chris Lattner42d1be02009-07-23 05:14:02 +00003933Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3934 FCmpInst *RHS) {
3935
3936 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3937 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3938 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3939 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3940 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3941 // If either of the constants are nans, then the whole thing returns
3942 // false.
3943 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003944 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003945 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003946 LHS->getOperand(0), RHS->getOperand(0));
3947 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003948
3949 // Handle vector zeros. This occurs because the canonical form of
3950 // "fcmp ord x,x" is "fcmp ord x, 0".
3951 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3952 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003953 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003954 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003955 return 0;
3956 }
3957
3958 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3959 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3960 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3961
3962
3963 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3964 // Swap RHS operands to match LHS.
3965 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3966 std::swap(Op1LHS, Op1RHS);
3967 }
3968
3969 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3970 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3971 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003972 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003973
3974 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003975 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003976 if (Op0CC == FCmpInst::FCMP_TRUE)
3977 return ReplaceInstUsesWith(I, RHS);
3978 if (Op1CC == FCmpInst::FCMP_TRUE)
3979 return ReplaceInstUsesWith(I, LHS);
3980
3981 bool Op0Ordered;
3982 bool Op1Ordered;
3983 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3984 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3985 if (Op1Pred == 0) {
3986 std::swap(LHS, RHS);
3987 std::swap(Op0Pred, Op1Pred);
3988 std::swap(Op0Ordered, Op1Ordered);
3989 }
3990 if (Op0Pred == 0) {
3991 // uno && ueq -> uno && (uno || eq) -> ueq
3992 // ord && olt -> ord && (ord && lt) -> olt
3993 if (Op0Ordered == Op1Ordered)
3994 return ReplaceInstUsesWith(I, RHS);
3995
3996 // uno && oeq -> uno && (ord && eq) -> false
3997 // uno && ord -> false
3998 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003999 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004000 // ord && ueq -> ord && (uno || eq) -> oeq
4001 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4002 Op0LHS, Op0RHS, Context));
4003 }
4004 }
4005
4006 return 0;
4007}
4008
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004009
Chris Lattner7e708292002-06-25 16:13:24 +00004010Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004011 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004013
Chris Lattnere87597f2004-10-16 18:11:37 +00004014 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004016
Chris Lattner6e7ba452005-01-01 16:22:27 +00004017 // and X, X = X
4018 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004019 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004020
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004021 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004022 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004023 if (SimplifyDemandedInstructionBits(I))
4024 return &I;
4025 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004026 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004027 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004028 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004029 } else if (isa<ConstantAggregateZero>(Op1)) {
4030 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004031 }
4032 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004033
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004034 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004035 const APInt& AndRHSMask = AndRHS->getValue();
4036 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004037
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004038 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004039 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004040 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004041 Value *Op0LHS = Op0I->getOperand(0);
4042 Value *Op0RHS = Op0I->getOperand(1);
4043 switch (Op0I->getOpcode()) {
4044 case Instruction::Xor:
4045 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004046 // If the mask is only needed on one incoming arm, push it up.
4047 if (Op0I->hasOneUse()) {
4048 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4049 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004050 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4051 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004052 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004053 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004054 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004055 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4057 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004058 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4059 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004060 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004061 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4062 }
4063 }
4064
Chris Lattner6e7ba452005-01-01 16:22:27 +00004065 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004066 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004067 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4068 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4069 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4070 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004071 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004072 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004073 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004074 break;
4075
4076 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004077 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4078 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4079 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4080 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004081 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004082
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004083 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4084 // has 1's for all bits that the subtraction with A might affect.
4085 if (Op0I->hasOneUse()) {
4086 uint32_t BitWidth = AndRHSMask.getBitWidth();
4087 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4088 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4089
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004090 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004091 if (!(A && A->isZero()) && // avoid infinite recursion.
4092 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004093 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004094 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4095 }
4096 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004097 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004098
4099 case Instruction::Shl:
4100 case Instruction::LShr:
4101 // (1 << x) & 1 --> zext(x == 0)
4102 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004103 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004104 Value *NewICmp =
4105 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004106 return new ZExtInst(NewICmp, I.getType());
4107 }
4108 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004109 }
4110
Chris Lattner58403262003-07-23 19:25:52 +00004111 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004112 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004113 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004115 // If this is an integer truncation or change from signed-to-unsigned, and
4116 // if the source is an and/or with immediate, transform it. This
4117 // frequently occurs for bitfield accesses.
4118 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004119 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004120 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004121 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004122 if (CastOp->getOpcode() == Instruction::And) {
4123 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004124 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4125 // This will fold the two constants together, which may allow
4126 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004127 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004128 CastOp->getOperand(0), I.getType(),
4129 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004130 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004131 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004132 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004133 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004134 } else if (CastOp->getOpcode() == Instruction::Or) {
4135 // Change: and (cast (or X, C1) to T), C2
4136 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004137 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004138 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004139 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004140 return ReplaceInstUsesWith(I, AndRHS);
4141 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004142 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004143 }
Chris Lattner06782f82003-07-23 19:36:21 +00004144 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004145
4146 // Try to fold constant and into select arguments.
4147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004149 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004150 if (isa<PHINode>(Op0))
4151 if (Instruction *NV = FoldOpIntoPhi(I))
4152 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004153 }
4154
Dan Gohman186a6362009-08-12 16:04:34 +00004155 Value *Op0NotVal = dyn_castNotVal(Op0);
4156 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004157
Chris Lattner5b62aa72004-06-18 06:07:51 +00004158 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004160
Misha Brukmancb6267b2004-07-30 12:50:08 +00004161 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004162 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004163 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4164 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004165 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004166 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004167
4168 {
Chris Lattner003b6202007-06-15 05:58:24 +00004169 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004170 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004171 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4172 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004173
4174 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004175 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004176 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004177 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004178 }
4179 }
4180
Dan Gohman4ae51262009-08-12 16:23:25 +00004181 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004182 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4183 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004184
4185 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004186 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004187 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004188 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004189 }
4190 }
Chris Lattner64daab52006-04-01 08:03:55 +00004191
4192 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004193 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004194 if (A == Op1) { // (A^B)&A -> A&(A^B)
4195 I.swapOperands(); // Simplify below
4196 std::swap(Op0, Op1);
4197 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4198 cast<BinaryOperator>(Op0)->swapOperands();
4199 I.swapOperands(); // Simplify below
4200 std::swap(Op0, Op1);
4201 }
4202 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004203
Chris Lattner64daab52006-04-01 08:03:55 +00004204 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004205 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004206 if (B == Op0) { // B&(A^B) -> B&(B^A)
4207 cast<BinaryOperator>(Op1)->swapOperands();
4208 std::swap(A, B);
4209 }
Chris Lattner74381062009-08-30 07:44:24 +00004210 if (A == Op0) // A&(A^B) -> A & ~B
4211 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004212 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004213
4214 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004215 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4216 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004217 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004218 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4219 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004220 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004221 }
4222
Reid Spencere4d87aa2006-12-23 06:05:41 +00004223 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4224 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004225 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004226 return R;
4227
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004228 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4229 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4230 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004231 }
4232
Chris Lattner6fc205f2006-05-05 06:39:07 +00004233 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004234 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4235 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4236 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4237 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004238 if (SrcTy == Op1C->getOperand(0)->getType() &&
4239 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004240 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004241 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4242 I.getType(), TD) &&
4243 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4244 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004245 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4246 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004247 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004248 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004249 }
Chris Lattnere511b742006-11-14 07:46:50 +00004250
4251 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004252 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4253 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4254 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004255 SI0->getOperand(1) == SI1->getOperand(1) &&
4256 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004257 Value *NewOp =
4258 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4259 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004260 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004261 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004262 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004263 }
4264
Evan Cheng8db90722008-10-14 17:15:11 +00004265 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004266 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004267 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4268 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4269 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004270 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004271
Chris Lattner7e708292002-06-25 16:13:24 +00004272 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004273}
4274
Chris Lattner8c34cd22008-10-05 02:13:19 +00004275/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4276/// capable of providing pieces of a bswap. The subexpression provides pieces
4277/// of a bswap if it is proven that each of the non-zero bytes in the output of
4278/// the expression came from the corresponding "byte swapped" byte in some other
4279/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4280/// we know that the expression deposits the low byte of %X into the high byte
4281/// of the bswap result and that all other bytes are zero. This expression is
4282/// accepted, the high byte of ByteValues is set to X to indicate a correct
4283/// match.
4284///
4285/// This function returns true if the match was unsuccessful and false if so.
4286/// On entry to the function the "OverallLeftShift" is a signed integer value
4287/// indicating the number of bytes that the subexpression is later shifted. For
4288/// example, if the expression is later right shifted by 16 bits, the
4289/// OverallLeftShift value would be -2 on entry. This is used to specify which
4290/// byte of ByteValues is actually being set.
4291///
4292/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4293/// byte is masked to zero by a user. For example, in (X & 255), X will be
4294/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4295/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4296/// always in the local (OverallLeftShift) coordinate space.
4297///
4298static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4299 SmallVector<Value*, 8> &ByteValues) {
4300 if (Instruction *I = dyn_cast<Instruction>(V)) {
4301 // If this is an or instruction, it may be an inner node of the bswap.
4302 if (I->getOpcode() == Instruction::Or) {
4303 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4304 ByteValues) ||
4305 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4306 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004307 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004308
4309 // If this is a logical shift by a constant multiple of 8, recurse with
4310 // OverallLeftShift and ByteMask adjusted.
4311 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4312 unsigned ShAmt =
4313 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4314 // Ensure the shift amount is defined and of a byte value.
4315 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4316 return true;
4317
4318 unsigned ByteShift = ShAmt >> 3;
4319 if (I->getOpcode() == Instruction::Shl) {
4320 // X << 2 -> collect(X, +2)
4321 OverallLeftShift += ByteShift;
4322 ByteMask >>= ByteShift;
4323 } else {
4324 // X >>u 2 -> collect(X, -2)
4325 OverallLeftShift -= ByteShift;
4326 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004327 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004328 }
4329
4330 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4331 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4332
4333 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4334 ByteValues);
4335 }
4336
4337 // If this is a logical 'and' with a mask that clears bytes, clear the
4338 // corresponding bytes in ByteMask.
4339 if (I->getOpcode() == Instruction::And &&
4340 isa<ConstantInt>(I->getOperand(1))) {
4341 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4342 unsigned NumBytes = ByteValues.size();
4343 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4344 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4345
4346 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4347 // If this byte is masked out by a later operation, we don't care what
4348 // the and mask is.
4349 if ((ByteMask & (1 << i)) == 0)
4350 continue;
4351
4352 // If the AndMask is all zeros for this byte, clear the bit.
4353 APInt MaskB = AndMask & Byte;
4354 if (MaskB == 0) {
4355 ByteMask &= ~(1U << i);
4356 continue;
4357 }
4358
4359 // If the AndMask is not all ones for this byte, it's not a bytezap.
4360 if (MaskB != Byte)
4361 return true;
4362
4363 // Otherwise, this byte is kept.
4364 }
4365
4366 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4367 ByteValues);
4368 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004369 }
4370
Chris Lattner8c34cd22008-10-05 02:13:19 +00004371 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4372 // the input value to the bswap. Some observations: 1) if more than one byte
4373 // is demanded from this input, then it could not be successfully assembled
4374 // into a byteswap. At least one of the two bytes would not be aligned with
4375 // their ultimate destination.
4376 if (!isPowerOf2_32(ByteMask)) return true;
4377 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004378
Chris Lattner8c34cd22008-10-05 02:13:19 +00004379 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4380 // is demanded, it needs to go into byte 0 of the result. This means that the
4381 // byte needs to be shifted until it lands in the right byte bucket. The
4382 // shift amount depends on the position: if the byte is coming from the high
4383 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4384 // low part, it must be shifted left.
4385 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4386 if (InputByteNo < ByteValues.size()/2) {
4387 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4388 return true;
4389 } else {
4390 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4391 return true;
4392 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004393
4394 // If the destination byte value is already defined, the values are or'd
4395 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004396 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004397 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004398 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004399 return false;
4400}
4401
4402/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4403/// If so, insert the new bswap intrinsic and return it.
4404Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004405 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004406 if (!ITy || ITy->getBitWidth() % 16 ||
4407 // ByteMask only allows up to 32-byte values.
4408 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004409 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004410
4411 /// ByteValues - For each byte of the result, we keep track of which value
4412 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004413 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004414 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004415
4416 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004417 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4418 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004419 return 0;
4420
4421 // Check to see if all of the bytes come from the same value.
4422 Value *V = ByteValues[0];
4423 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4424
4425 // Check to make sure that all of the bytes come from the same value.
4426 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4427 if (ByteValues[i] != V)
4428 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004429 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004430 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004431 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004432 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004433}
4434
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004435/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4436/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4437/// we can simplify this expression to "cond ? C : D or B".
4438static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004439 Value *C, Value *D,
4440 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004441 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004442 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004443 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004444 return 0;
4445
Chris Lattnera6a474d2008-11-16 04:26:55 +00004446 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004447 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004448 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004449 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004450 return SelectInst::Create(Cond, C, B);
4451 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004452 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004453 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004454 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004455 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004456 return 0;
4457}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004458
Chris Lattner69d4ced2008-11-16 05:20:07 +00004459/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4460Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4461 ICmpInst *LHS, ICmpInst *RHS) {
4462 Value *Val, *Val2;
4463 ConstantInt *LHSCst, *RHSCst;
4464 ICmpInst::Predicate LHSCC, RHSCC;
4465
4466 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004467 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004468 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004469 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004470 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004471 return 0;
4472
4473 // From here on, we only handle:
4474 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4475 if (Val != Val2) return 0;
4476
4477 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4478 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4479 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4480 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4481 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4482 return 0;
4483
4484 // We can't fold (ugt x, C) | (sgt x, C2).
4485 if (!PredicatesFoldable(LHSCC, RHSCC))
4486 return 0;
4487
4488 // Ensure that the larger constant is on the RHS.
4489 bool ShouldSwap;
4490 if (ICmpInst::isSignedPredicate(LHSCC) ||
4491 (ICmpInst::isEquality(LHSCC) &&
4492 ICmpInst::isSignedPredicate(RHSCC)))
4493 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4494 else
4495 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4496
4497 if (ShouldSwap) {
4498 std::swap(LHS, RHS);
4499 std::swap(LHSCst, RHSCst);
4500 std::swap(LHSCC, RHSCC);
4501 }
4502
4503 // At this point, we know we have have two icmp instructions
4504 // comparing a value against two constants and or'ing the result
4505 // together. Because of the above check, we know that we only have
4506 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4507 // FoldICmpLogical check above), that the two constants are not
4508 // equal.
4509 assert(LHSCst != RHSCst && "Compares not folded above?");
4510
4511 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004512 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004513 case ICmpInst::ICMP_EQ:
4514 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004515 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004516 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004517 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004518 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004519 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004520 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004521 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004522 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004523 }
4524 break; // (X == 13 | X == 15) -> no change
4525 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4526 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4527 break;
4528 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4529 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4530 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4531 return ReplaceInstUsesWith(I, RHS);
4532 }
4533 break;
4534 case ICmpInst::ICMP_NE:
4535 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004536 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004537 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4538 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4539 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4540 return ReplaceInstUsesWith(I, LHS);
4541 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4542 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4543 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004544 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004545 }
4546 break;
4547 case ICmpInst::ICMP_ULT:
4548 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004549 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004550 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4551 break;
4552 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4553 // If RHSCst is [us]MAXINT, it is always false. Not handling
4554 // this can cause overflow.
4555 if (RHSCst->isMaxValue(false))
4556 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004557 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004558 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004559 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4560 break;
4561 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4562 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4563 return ReplaceInstUsesWith(I, RHS);
4564 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4565 break;
4566 }
4567 break;
4568 case ICmpInst::ICMP_SLT:
4569 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004570 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4572 break;
4573 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4574 // If RHSCst is [us]MAXINT, it is always false. Not handling
4575 // this can cause overflow.
4576 if (RHSCst->isMaxValue(true))
4577 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004578 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004579 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4581 break;
4582 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4583 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4584 return ReplaceInstUsesWith(I, RHS);
4585 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4586 break;
4587 }
4588 break;
4589 case ICmpInst::ICMP_UGT:
4590 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004591 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4593 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4594 return ReplaceInstUsesWith(I, LHS);
4595 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4596 break;
4597 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4598 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004599 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004600 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4601 break;
4602 }
4603 break;
4604 case ICmpInst::ICMP_SGT:
4605 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004606 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004607 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4608 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4609 return ReplaceInstUsesWith(I, LHS);
4610 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4611 break;
4612 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4613 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004614 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004615 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4616 break;
4617 }
4618 break;
4619 }
4620 return 0;
4621}
4622
Chris Lattner5414cc52009-07-23 05:46:22 +00004623Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4624 FCmpInst *RHS) {
4625 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4626 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4627 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4628 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4629 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4630 // If either of the constants are nans, then the whole thing returns
4631 // true.
4632 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004633 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004634
4635 // Otherwise, no need to compare the two constants, compare the
4636 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004637 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004638 LHS->getOperand(0), RHS->getOperand(0));
4639 }
4640
4641 // Handle vector zeros. This occurs because the canonical form of
4642 // "fcmp uno x,x" is "fcmp uno x, 0".
4643 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4644 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004645 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004646 LHS->getOperand(0), RHS->getOperand(0));
4647
4648 return 0;
4649 }
4650
4651 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4652 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4653 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4654
4655 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4656 // Swap RHS operands to match LHS.
4657 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4658 std::swap(Op1LHS, Op1RHS);
4659 }
4660 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4661 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4662 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004663 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004664 Op0LHS, Op0RHS);
4665 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004666 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004667 if (Op0CC == FCmpInst::FCMP_FALSE)
4668 return ReplaceInstUsesWith(I, RHS);
4669 if (Op1CC == FCmpInst::FCMP_FALSE)
4670 return ReplaceInstUsesWith(I, LHS);
4671 bool Op0Ordered;
4672 bool Op1Ordered;
4673 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4674 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4675 if (Op0Ordered == Op1Ordered) {
4676 // If both are ordered or unordered, return a new fcmp with
4677 // or'ed predicates.
4678 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4679 Op0LHS, Op0RHS, Context);
4680 if (Instruction *I = dyn_cast<Instruction>(RV))
4681 return I;
4682 // Otherwise, it's a constant boolean value...
4683 return ReplaceInstUsesWith(I, RV);
4684 }
4685 }
4686 return 0;
4687}
4688
Bill Wendlinga698a472008-12-01 08:23:25 +00004689/// FoldOrWithConstants - This helper function folds:
4690///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004691/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004692///
4693/// into:
4694///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004695/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004696///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004697/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004698Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004699 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004700 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4701 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004702
Bill Wendling286a0542008-12-02 06:24:20 +00004703 Value *V1 = 0;
4704 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004705 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004706
Bill Wendling29976b92008-12-02 06:18:11 +00004707 APInt Xor = CI1->getValue() ^ CI2->getValue();
4708 if (!Xor.isAllOnesValue()) return 0;
4709
Bill Wendling286a0542008-12-02 06:24:20 +00004710 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004711 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004712 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004713 }
4714
4715 return 0;
4716}
4717
Chris Lattner7e708292002-06-25 16:13:24 +00004718Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004719 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004720 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004721
Chris Lattner42593e62007-03-24 23:56:43 +00004722 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004723 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004724
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004725 // or X, X = X
4726 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004727 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004728
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004729 // See if we can simplify any instructions used by the instruction whose sole
4730 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004731 if (SimplifyDemandedInstructionBits(I))
4732 return &I;
4733 if (isa<VectorType>(I.getType())) {
4734 if (isa<ConstantAggregateZero>(Op1)) {
4735 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4736 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4737 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4738 return ReplaceInstUsesWith(I, I.getOperand(1));
4739 }
Chris Lattner42593e62007-03-24 23:56:43 +00004740 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004741
Chris Lattner3f5b8772002-05-06 16:14:14 +00004742 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004743 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004744 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004745 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004746 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004747 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004748 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004749 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004750 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004751 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004752 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004753
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004754 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004755 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004756 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004757 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004758 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004759 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004760 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004761 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004762
4763 // Try to fold constant and into select arguments.
4764 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004765 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004766 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004767 if (isa<PHINode>(Op0))
4768 if (Instruction *NV = FoldOpIntoPhi(I))
4769 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004770 }
4771
Chris Lattner4f637d42006-01-06 17:59:59 +00004772 Value *A = 0, *B = 0;
4773 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004774
Dan Gohman4ae51262009-08-12 16:23:25 +00004775 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004776 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4777 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004778 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004779 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4780 return ReplaceInstUsesWith(I, Op0);
4781
Chris Lattner6423d4c2006-07-10 20:25:24 +00004782 // (A | B) | C and A | (B | C) -> bswap if possible.
4783 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004784 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4785 match(Op1, m_Or(m_Value(), m_Value())) ||
4786 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4787 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004788 if (Instruction *BSwap = MatchBSwap(I))
4789 return BSwap;
4790 }
4791
Chris Lattner6e4c6492005-05-09 04:58:36 +00004792 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004793 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004794 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004795 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004796 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004797 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004798 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004799 }
4800
4801 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004802 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004803 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004804 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004805 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004806 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004807 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004808 }
4809
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004810 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004811 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004812 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4813 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004814 Value *V1 = 0, *V2 = 0, *V3 = 0;
4815 C1 = dyn_cast<ConstantInt>(C);
4816 C2 = dyn_cast<ConstantInt>(D);
4817 if (C1 && C2) { // (A & C1)|(B & C2)
4818 // If we have: ((V + N) & C1) | (V & C2)
4819 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4820 // replace with V+N.
4821 if (C1->getValue() == ~C2->getValue()) {
4822 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004823 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004824 // Add commutes, try both ways.
4825 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4826 return ReplaceInstUsesWith(I, A);
4827 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4828 return ReplaceInstUsesWith(I, A);
4829 }
4830 // Or commutes, try both ways.
4831 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004832 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004833 // Add commutes, try both ways.
4834 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4835 return ReplaceInstUsesWith(I, B);
4836 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4837 return ReplaceInstUsesWith(I, B);
4838 }
4839 }
Chris Lattner044e5332007-04-08 08:01:49 +00004840 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004841 }
4842
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004843 // Check to see if we have any common things being and'ed. If so, find the
4844 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004845 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4846 if (A == B) // (A & C)|(A & D) == A & (C|D)
4847 V1 = A, V2 = C, V3 = D;
4848 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4849 V1 = A, V2 = B, V3 = C;
4850 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4851 V1 = C, V2 = A, V3 = D;
4852 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4853 V1 = C, V2 = A, V3 = B;
4854
4855 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004856 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004857 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004858 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004859 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004860
Dan Gohman1975d032008-10-30 20:40:10 +00004861 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004862 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004863 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004864 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004865 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004866 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004867 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004868 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004869 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004870
Bill Wendlingb01865c2008-11-30 13:52:49 +00004871 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004872 if ((match(C, m_Not(m_Specific(D))) &&
4873 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004874 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004875 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004876 if ((match(A, m_Not(m_Specific(D))) &&
4877 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004878 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004879 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004880 if ((match(C, m_Not(m_Specific(B))) &&
4881 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004882 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004883 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004884 if ((match(A, m_Not(m_Specific(B))) &&
4885 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004886 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004887 }
Chris Lattnere511b742006-11-14 07:46:50 +00004888
4889 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004890 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4891 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4892 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004893 SI0->getOperand(1) == SI1->getOperand(1) &&
4894 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004895 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4896 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004897 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004898 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004899 }
4900 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004901
Bill Wendlingb3833d12008-12-01 01:07:11 +00004902 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004903 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4904 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004905 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004906 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004907 }
4908 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004909 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4910 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004911 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004912 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004913 }
4914
Dan Gohman4ae51262009-08-12 16:23:25 +00004915 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004916 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004917 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004918 } else {
4919 A = 0;
4920 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004921 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004922 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004923 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004924 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004925
Misha Brukmancb6267b2004-07-30 12:50:08 +00004926 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004927 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004928 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004929 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004930 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004931 }
Chris Lattnera2881962003-02-18 19:28:33 +00004932
Reid Spencere4d87aa2006-12-23 06:05:41 +00004933 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4934 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004935 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004936 return R;
4937
Chris Lattner69d4ced2008-11-16 05:20:07 +00004938 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4939 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4940 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004941 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004942
4943 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004944 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004945 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004946 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004947 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4948 !isa<ICmpInst>(Op1C->getOperand(0))) {
4949 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004950 if (SrcTy == Op1C->getOperand(0)->getType() &&
4951 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004952 // Only do this if the casts both really cause code to be
4953 // generated.
4954 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4955 I.getType(), TD) &&
4956 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4957 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004958 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4959 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004960 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004961 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004962 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004963 }
Chris Lattner99c65742007-10-24 05:38:08 +00004964 }
4965
4966
4967 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4968 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004969 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4970 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4971 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004972 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004973
Chris Lattner7e708292002-06-25 16:13:24 +00004974 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004975}
4976
Dan Gohman844731a2008-05-13 00:00:25 +00004977namespace {
4978
Chris Lattnerc317d392004-02-16 01:20:27 +00004979// XorSelf - Implements: X ^ X --> 0
4980struct XorSelf {
4981 Value *RHS;
4982 XorSelf(Value *rhs) : RHS(rhs) {}
4983 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4984 Instruction *apply(BinaryOperator &Xor) const {
4985 return &Xor;
4986 }
4987};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004988
Dan Gohman844731a2008-05-13 00:00:25 +00004989}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004990
Chris Lattner7e708292002-06-25 16:13:24 +00004991Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004992 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004994
Evan Chengd34af782008-03-25 20:07:13 +00004995 if (isa<UndefValue>(Op1)) {
4996 if (isa<UndefValue>(Op0))
4997 // Handle undef ^ undef -> 0 special case. This is a common
4998 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00004999 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005000 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005001 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005002
Chris Lattnerc317d392004-02-16 01:20:27 +00005003 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005004 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005005 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005006 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005007 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005008
5009 // See if we can simplify any instructions used by the instruction whose sole
5010 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005011 if (SimplifyDemandedInstructionBits(I))
5012 return &I;
5013 if (isa<VectorType>(I.getType()))
5014 if (isa<ConstantAggregateZero>(Op1))
5015 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005016
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005017 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005018 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005019 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5020 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5021 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5022 if (Op0I->getOpcode() == Instruction::And ||
5023 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005024 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5025 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005026 Value *NotY =
5027 Builder->CreateNot(Op0I->getOperand(1),
5028 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005029 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005030 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005031 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005032 }
5033 }
5034 }
5035 }
5036
5037
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005038 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005039 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005040 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005041 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005042 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005043 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005044
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005045 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005046 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005047 FCI->getOperand(0), FCI->getOperand(1));
5048 }
5049
Nick Lewycky517e1f52008-05-31 19:01:33 +00005050 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5051 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5052 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5053 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5054 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005055 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5056 (RHS == ConstantExpr::getCast(Opcode,
5057 ConstantInt::getTrue(*Context),
5058 Op0C->getDestTy()))) {
5059 CI->setPredicate(CI->getInversePredicate());
5060 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005061 }
5062 }
5063 }
5064 }
5065
Reid Spencere4d87aa2006-12-23 06:05:41 +00005066 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005067 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005068 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5069 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005070 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5071 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005072 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005073 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005074 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005075
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005076 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005077 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005078 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005079 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005080 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005081 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005082 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005083 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005084 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005085 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005086 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005087 Constant *C = ConstantInt::get(*Context,
5088 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005089 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005090
Chris Lattner7c4049c2004-01-12 19:35:11 +00005091 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005092 } else if (Op0I->getOpcode() == Instruction::Or) {
5093 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005094 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005095 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005096 // Anything in both C1 and C2 is known to be zero, remove it from
5097 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005098 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5099 NewRHS = ConstantExpr::getAnd(NewRHS,
5100 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005101 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005102 I.setOperand(0, Op0I->getOperand(0));
5103 I.setOperand(1, NewRHS);
5104 return &I;
5105 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005106 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005107 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005108 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005109
5110 // Try to fold constant and into select arguments.
5111 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005112 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005113 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005114 if (isa<PHINode>(Op0))
5115 if (Instruction *NV = FoldOpIntoPhi(I))
5116 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005117 }
5118
Dan Gohman186a6362009-08-12 16:04:34 +00005119 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005120 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005121 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005122
Dan Gohman186a6362009-08-12 16:04:34 +00005123 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005124 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005125 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005126
Chris Lattner318bf792007-03-18 22:51:34 +00005127
5128 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5129 if (Op1I) {
5130 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005131 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005132 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005133 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005134 I.swapOperands();
5135 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005136 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005137 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005138 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005139 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005140 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005141 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005142 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005143 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005144 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005145 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005146 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005147 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005148 std::swap(A, B);
5149 }
Chris Lattner318bf792007-03-18 22:51:34 +00005150 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005151 I.swapOperands(); // Simplified below.
5152 std::swap(Op0, Op1);
5153 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005154 }
Chris Lattner318bf792007-03-18 22:51:34 +00005155 }
5156
5157 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5158 if (Op0I) {
5159 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005160 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005161 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005162 if (A == Op1) // (B|A)^B == (A|B)^B
5163 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005164 if (B == Op1) // (A|B)^B == A & ~B
5165 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005166 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005167 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005168 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005169 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005170 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005171 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005172 if (A == Op1) // (A&B)^A -> (B&A)^A
5173 std::swap(A, B);
5174 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005175 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005176 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005177 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005178 }
Chris Lattner318bf792007-03-18 22:51:34 +00005179 }
5180
5181 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5182 if (Op0I && Op1I && Op0I->isShift() &&
5183 Op0I->getOpcode() == Op1I->getOpcode() &&
5184 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5185 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005186 Value *NewOp =
5187 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5188 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005189 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005190 Op1I->getOperand(1));
5191 }
5192
5193 if (Op0I && Op1I) {
5194 Value *A, *B, *C, *D;
5195 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005196 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5197 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005198 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005199 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005200 }
5201 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005202 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5203 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005204 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005205 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005206 }
5207
5208 // (A & B)^(C & D)
5209 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005210 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5211 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005212 // (X & Y)^(X & Y) -> (Y^Z) & X
5213 Value *X = 0, *Y = 0, *Z = 0;
5214 if (A == C)
5215 X = A, Y = B, Z = D;
5216 else if (A == D)
5217 X = A, Y = B, Z = C;
5218 else if (B == C)
5219 X = B, Y = A, Z = D;
5220 else if (B == D)
5221 X = B, Y = A, Z = C;
5222
5223 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005224 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005225 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005226 }
5227 }
5228 }
5229
Reid Spencere4d87aa2006-12-23 06:05:41 +00005230 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5231 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005232 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005233 return R;
5234
Chris Lattner6fc205f2006-05-05 06:39:07 +00005235 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005236 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005237 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005238 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5239 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005240 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005241 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005242 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5243 I.getType(), TD) &&
5244 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5245 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005246 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5247 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005248 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005249 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005250 }
Chris Lattner99c65742007-10-24 05:38:08 +00005251 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005252
Chris Lattner7e708292002-06-25 16:13:24 +00005253 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005254}
5255
Owen Andersond672ecb2009-07-03 00:17:18 +00005256static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005257 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005258 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005259}
Chris Lattnera96879a2004-09-29 17:40:11 +00005260
Dan Gohman6de29f82009-06-15 22:12:54 +00005261static bool HasAddOverflow(ConstantInt *Result,
5262 ConstantInt *In1, ConstantInt *In2,
5263 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005264 if (IsSigned)
5265 if (In2->getValue().isNegative())
5266 return Result->getValue().sgt(In1->getValue());
5267 else
5268 return Result->getValue().slt(In1->getValue());
5269 else
5270 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005271}
5272
Dan Gohman6de29f82009-06-15 22:12:54 +00005273/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005274/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005275static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005276 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005277 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005278 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005279
Dan Gohman6de29f82009-06-15 22:12:54 +00005280 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5281 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005282 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005283 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5284 ExtractElement(In1, Idx, Context),
5285 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005286 IsSigned))
5287 return true;
5288 }
5289 return false;
5290 }
5291
5292 return HasAddOverflow(cast<ConstantInt>(Result),
5293 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5294 IsSigned);
5295}
5296
5297static bool HasSubOverflow(ConstantInt *Result,
5298 ConstantInt *In1, ConstantInt *In2,
5299 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005300 if (IsSigned)
5301 if (In2->getValue().isNegative())
5302 return Result->getValue().slt(In1->getValue());
5303 else
5304 return Result->getValue().sgt(In1->getValue());
5305 else
5306 return Result->getValue().ugt(In1->getValue());
5307}
5308
Dan Gohman6de29f82009-06-15 22:12:54 +00005309/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5310/// overflowed for this type.
5311static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005312 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005313 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005314 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005315
5316 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5317 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005318 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005319 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5320 ExtractElement(In1, Idx, Context),
5321 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005322 IsSigned))
5323 return true;
5324 }
5325 return false;
5326 }
5327
5328 return HasSubOverflow(cast<ConstantInt>(Result),
5329 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5330 IsSigned);
5331}
5332
Chris Lattner574da9b2005-01-13 20:14:25 +00005333/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5334/// code necessary to compute the offset from the base pointer (without adding
5335/// in the base pointer). Return the result as a signed integer of intptr size.
5336static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005337 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005338 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005339 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005340 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005341
5342 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005343 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005344 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005345
Gabor Greif177dd3f2008-06-12 21:37:33 +00005346 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5347 ++i, ++GTI) {
5348 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005349 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005350 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5351 if (OpC->isZero()) continue;
5352
5353 // Handle a struct index, which adds its field offset to the pointer.
5354 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5355 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5356
Chris Lattner74381062009-08-30 07:44:24 +00005357 Result = IC.Builder->CreateAdd(Result,
5358 ConstantInt::get(IntPtrTy, Size),
5359 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005360 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005361 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005362
Owen Andersoneed707b2009-07-24 23:12:02 +00005363 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005364 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005365 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5366 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005367 // Emit an add instruction.
5368 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005369 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005370 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005371 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005372 if (Op->getType() != IntPtrTy)
5373 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005374 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005375 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005376 // We'll let instcombine(mul) convert this to a shl if possible.
5377 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005378 }
5379
5380 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005381 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005382 }
5383 return Result;
5384}
5385
Chris Lattner10c0d912008-04-22 02:53:33 +00005386
Dan Gohman8f080f02009-07-17 22:16:21 +00005387/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5388/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5389/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5390/// be complex, and scales are involved. The above expression would also be
5391/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5392/// This later form is less amenable to optimization though, and we are allowed
5393/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005394///
5395/// If we can't emit an optimized form for this expression, this returns null.
5396///
5397static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5398 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005399 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005400 gep_type_iterator GTI = gep_type_begin(GEP);
5401
5402 // Check to see if this gep only has a single variable index. If so, and if
5403 // any constant indices are a multiple of its scale, then we can compute this
5404 // in terms of the scale of the variable index. For example, if the GEP
5405 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5406 // because the expression will cross zero at the same point.
5407 unsigned i, e = GEP->getNumOperands();
5408 int64_t Offset = 0;
5409 for (i = 1; i != e; ++i, ++GTI) {
5410 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5411 // Compute the aggregate offset of constant indices.
5412 if (CI->isZero()) continue;
5413
5414 // Handle a struct index, which adds its field offset to the pointer.
5415 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5416 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5417 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005418 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005419 Offset += Size*CI->getSExtValue();
5420 }
5421 } else {
5422 // Found our variable index.
5423 break;
5424 }
5425 }
5426
5427 // If there are no variable indices, we must have a constant offset, just
5428 // evaluate it the general way.
5429 if (i == e) return 0;
5430
5431 Value *VariableIdx = GEP->getOperand(i);
5432 // Determine the scale factor of the variable element. For example, this is
5433 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005434 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005435
5436 // Verify that there are no other variable indices. If so, emit the hard way.
5437 for (++i, ++GTI; i != e; ++i, ++GTI) {
5438 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5439 if (!CI) return 0;
5440
5441 // Compute the aggregate offset of constant indices.
5442 if (CI->isZero()) continue;
5443
5444 // Handle a struct index, which adds its field offset to the pointer.
5445 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5446 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5447 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005448 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005449 Offset += Size*CI->getSExtValue();
5450 }
5451 }
5452
5453 // Okay, we know we have a single variable index, which must be a
5454 // pointer/array/vector index. If there is no offset, life is simple, return
5455 // the index.
5456 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5457 if (Offset == 0) {
5458 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5459 // we don't need to bother extending: the extension won't affect where the
5460 // computation crosses zero.
5461 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005462 VariableIdx = new TruncInst(VariableIdx,
5463 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005464 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005465 return VariableIdx;
5466 }
5467
5468 // Otherwise, there is an index. The computation we will do will be modulo
5469 // the pointer size, so get it.
5470 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5471
5472 Offset &= PtrSizeMask;
5473 VariableScale &= PtrSizeMask;
5474
5475 // To do this transformation, any constant index must be a multiple of the
5476 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5477 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5478 // multiple of the variable scale.
5479 int64_t NewOffs = Offset / (int64_t)VariableScale;
5480 if (Offset != NewOffs*(int64_t)VariableScale)
5481 return 0;
5482
5483 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005484 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005485 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005486 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005487 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005488 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005489 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005490 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005491}
5492
5493
Reid Spencere4d87aa2006-12-23 06:05:41 +00005494/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005495/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005496Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005497 ICmpInst::Predicate Cond,
5498 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005499 // Look through bitcasts.
5500 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5501 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005502
Chris Lattner574da9b2005-01-13 20:14:25 +00005503 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005504 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005505 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005506 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005507 // know pointers can't overflow since the gep is inbounds. See if we can
5508 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005509 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5510
5511 // If not, synthesize the offset the hard way.
5512 if (Offset == 0)
5513 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005514 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005515 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005516 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005517 // If the base pointers are different, but the indices are the same, just
5518 // compare the base pointer.
5519 if (PtrBase != GEPRHS->getOperand(0)) {
5520 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005521 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005522 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005523 if (IndicesTheSame)
5524 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5525 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5526 IndicesTheSame = false;
5527 break;
5528 }
5529
5530 // If all indices are the same, just compare the base pointers.
5531 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005532 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005533 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005534
5535 // Otherwise, the base pointers are different and the indices are
5536 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005537 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005538 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005539
Chris Lattnere9d782b2005-01-13 22:25:21 +00005540 // If one of the GEPs has all zero indices, recurse.
5541 bool AllZeros = true;
5542 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5543 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5544 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5545 AllZeros = false;
5546 break;
5547 }
5548 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005549 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5550 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005551
5552 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005553 AllZeros = true;
5554 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5555 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5556 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5557 AllZeros = false;
5558 break;
5559 }
5560 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005561 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005562
Chris Lattner4401c9c2005-01-14 00:20:05 +00005563 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5564 // If the GEPs only differ by one index, compare it.
5565 unsigned NumDifferences = 0; // Keep track of # differences.
5566 unsigned DiffOperand = 0; // The operand that differs.
5567 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5568 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005569 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5570 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005571 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005572 NumDifferences = 2;
5573 break;
5574 } else {
5575 if (NumDifferences++) break;
5576 DiffOperand = i;
5577 }
5578 }
5579
5580 if (NumDifferences == 0) // SAME GEP?
5581 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005582 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005583 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005584
Chris Lattner4401c9c2005-01-14 00:20:05 +00005585 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005586 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5587 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005589 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005590 }
5591 }
5592
Reid Spencere4d87aa2006-12-23 06:05:41 +00005593 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005594 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005595 if (TD &&
5596 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005597 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5598 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5599 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5600 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005601 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005602 }
5603 }
5604 return 0;
5605}
5606
Chris Lattnera5406232008-05-19 20:18:56 +00005607/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5608///
5609Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5610 Instruction *LHSI,
5611 Constant *RHSC) {
5612 if (!isa<ConstantFP>(RHSC)) return 0;
5613 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5614
5615 // Get the width of the mantissa. We don't want to hack on conversions that
5616 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005617 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005618 if (MantissaWidth == -1) return 0; // Unknown.
5619
5620 // Check to see that the input is converted from an integer type that is small
5621 // enough that preserves all bits. TODO: check here for "known" sign bits.
5622 // 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 +00005623 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005624
5625 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005626 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5627 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005628 ++InputSize;
5629
5630 // If the conversion would lose info, don't hack on this.
5631 if ((int)InputSize > MantissaWidth)
5632 return 0;
5633
5634 // Otherwise, we can potentially simplify the comparison. We know that it
5635 // will always come through as an integer value and we know the constant is
5636 // not a NAN (it would have been previously simplified).
5637 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5638
5639 ICmpInst::Predicate Pred;
5640 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005641 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005642 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005643 case FCmpInst::FCMP_OEQ:
5644 Pred = ICmpInst::ICMP_EQ;
5645 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005646 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005647 case FCmpInst::FCMP_OGT:
5648 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5649 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005650 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005651 case FCmpInst::FCMP_OGE:
5652 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5653 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005654 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005655 case FCmpInst::FCMP_OLT:
5656 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5657 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005658 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005659 case FCmpInst::FCMP_OLE:
5660 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5661 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005662 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005663 case FCmpInst::FCMP_ONE:
5664 Pred = ICmpInst::ICMP_NE;
5665 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005666 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005667 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005668 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005669 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005670 }
5671
5672 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5673
5674 // Now we know that the APFloat is a normal number, zero or inf.
5675
Chris Lattner85162782008-05-20 03:50:52 +00005676 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005677 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005678 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005679
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005680 if (!LHSUnsigned) {
5681 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5682 // and large values.
5683 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5684 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5685 APFloat::rmNearestTiesToEven);
5686 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5687 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5688 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005689 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5690 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005691 }
5692 } else {
5693 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5694 // +INF and large values.
5695 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5696 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5697 APFloat::rmNearestTiesToEven);
5698 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5699 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5700 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005701 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5702 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005703 }
Chris Lattnera5406232008-05-19 20:18:56 +00005704 }
5705
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005706 if (!LHSUnsigned) {
5707 // See if the RHS value is < SignedMin.
5708 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5709 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5710 APFloat::rmNearestTiesToEven);
5711 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5712 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5713 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005714 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5715 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005716 }
Chris Lattnera5406232008-05-19 20:18:56 +00005717 }
5718
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005719 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5720 // [0, UMAX], but it may still be fractional. See if it is fractional by
5721 // casting the FP value to the integer value and back, checking for equality.
5722 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005723 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005724 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5725 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005726 if (!RHS.isZero()) {
5727 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005728 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5729 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005730 if (!Equal) {
5731 // If we had a comparison against a fractional value, we have to adjust
5732 // the compare predicate and sometimes the value. RHSC is rounded towards
5733 // zero at this point.
5734 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005735 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005736 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005737 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005738 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005739 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005740 case ICmpInst::ICMP_ULE:
5741 // (float)int <= 4.4 --> int <= 4
5742 // (float)int <= -4.4 --> false
5743 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005744 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005745 break;
5746 case ICmpInst::ICMP_SLE:
5747 // (float)int <= 4.4 --> int <= 4
5748 // (float)int <= -4.4 --> int < -4
5749 if (RHS.isNegative())
5750 Pred = ICmpInst::ICMP_SLT;
5751 break;
5752 case ICmpInst::ICMP_ULT:
5753 // (float)int < -4.4 --> false
5754 // (float)int < 4.4 --> int <= 4
5755 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005757 Pred = ICmpInst::ICMP_ULE;
5758 break;
5759 case ICmpInst::ICMP_SLT:
5760 // (float)int < -4.4 --> int < -4
5761 // (float)int < 4.4 --> int <= 4
5762 if (!RHS.isNegative())
5763 Pred = ICmpInst::ICMP_SLE;
5764 break;
5765 case ICmpInst::ICMP_UGT:
5766 // (float)int > 4.4 --> int > 4
5767 // (float)int > -4.4 --> true
5768 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005769 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005770 break;
5771 case ICmpInst::ICMP_SGT:
5772 // (float)int > 4.4 --> int > 4
5773 // (float)int > -4.4 --> int >= -4
5774 if (RHS.isNegative())
5775 Pred = ICmpInst::ICMP_SGE;
5776 break;
5777 case ICmpInst::ICMP_UGE:
5778 // (float)int >= -4.4 --> true
5779 // (float)int >= 4.4 --> int > 4
5780 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005781 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005782 Pred = ICmpInst::ICMP_UGT;
5783 break;
5784 case ICmpInst::ICMP_SGE:
5785 // (float)int >= -4.4 --> int >= -4
5786 // (float)int >= 4.4 --> int > 4
5787 if (!RHS.isNegative())
5788 Pred = ICmpInst::ICMP_SGT;
5789 break;
5790 }
Chris Lattnera5406232008-05-19 20:18:56 +00005791 }
5792 }
5793
5794 // Lower this FP comparison into an appropriate integer version of the
5795 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005796 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005797}
5798
Reid Spencere4d87aa2006-12-23 06:05:41 +00005799Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5800 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005801 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005802
Chris Lattner58e97462007-01-14 19:42:17 +00005803 // Fold trivial predicates.
5804 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005805 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005806 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005807 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005808
5809 // Simplify 'fcmp pred X, X'
5810 if (Op0 == Op1) {
5811 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005812 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005813 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5814 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5815 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005816 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005817 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5818 case FCmpInst::FCMP_OLT: // True if ordered and less than
5819 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005820 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005821
5822 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5823 case FCmpInst::FCMP_ULT: // True if unordered or less than
5824 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5825 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5826 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5827 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005828 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005829 return &I;
5830
5831 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5832 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5833 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5834 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5835 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5836 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005837 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005838 return &I;
5839 }
5840 }
5841
Reid Spencere4d87aa2006-12-23 06:05:41 +00005842 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005843 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005844
Reid Spencere4d87aa2006-12-23 06:05:41 +00005845 // Handle fcmp with constant RHS
5846 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005847 // If the constant is a nan, see if we can fold the comparison based on it.
5848 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5849 if (CFP->getValueAPF().isNaN()) {
5850 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005852 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5853 "Comparison must be either ordered or unordered!");
5854 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005855 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005856 }
5857 }
5858
Reid Spencere4d87aa2006-12-23 06:05:41 +00005859 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5860 switch (LHSI->getOpcode()) {
5861 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005862 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5863 // block. If in the same block, we're encouraging jump threading. If
5864 // not, we are just pessimizing the code by making an i1 phi.
5865 if (LHSI->getParent() == I.getParent())
5866 if (Instruction *NV = FoldOpIntoPhi(I))
5867 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005868 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005869 case Instruction::SIToFP:
5870 case Instruction::UIToFP:
5871 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5872 return NV;
5873 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005874 case Instruction::Select:
5875 // If either operand of the select is a constant, we can fold the
5876 // comparison into the select arms, which will cause one to be
5877 // constant folded and the select turned into a bitwise or.
5878 Value *Op1 = 0, *Op2 = 0;
5879 if (LHSI->hasOneUse()) {
5880 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5881 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005882 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005883 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005884 Op2 = Builder->CreateFCmp(I.getPredicate(),
5885 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5887 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005888 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005889 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005890 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5891 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 }
5893 }
5894
5895 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005896 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005897 break;
5898 }
5899 }
5900
5901 return Changed ? &I : 0;
5902}
5903
5904Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5905 bool Changed = SimplifyCompare(I);
5906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5907 const Type *Ty = Op0->getType();
5908
5909 // icmp X, X
5910 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005911 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005912 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005913
5914 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005915 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005916
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005918 // addresses never equal each other! We already know that Op0 != Op1.
Victor Hernandez83d63912009-09-18 22:35:49 +00005919 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || isMalloc(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005920 isa<ConstantPointerNull>(Op0)) &&
Victor Hernandez83d63912009-09-18 22:35:49 +00005921 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || isMalloc(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005922 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005923 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005924 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005925
Reid Spencere4d87aa2006-12-23 06:05:41 +00005926 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005927 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005929 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005930 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005931 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005932 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005933 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005934 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005935 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005936
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005938 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005939 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005940 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005941 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005942 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005943 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005944 case ICmpInst::ICMP_SGT:
5945 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005946 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005947 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005948 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005949 return BinaryOperator::CreateAnd(Not, Op0);
5950 }
5951 case ICmpInst::ICMP_UGE:
5952 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5953 // FALL THROUGH
5954 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005955 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005956 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005957 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005958 case ICmpInst::ICMP_SGE:
5959 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5960 // FALL THROUGH
5961 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005962 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005963 return BinaryOperator::CreateOr(Not, Op0);
5964 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005965 }
Chris Lattner8b170942002-08-09 23:47:40 +00005966 }
5967
Dan Gohman1c8491e2009-04-25 17:12:48 +00005968 unsigned BitWidth = 0;
5969 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005970 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5971 else if (Ty->isIntOrIntVector())
5972 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005973
5974 bool isSignBit = false;
5975
Dan Gohman81b28ce2008-09-16 18:46:06 +00005976 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005977 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005978 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005979
Chris Lattnerb6566012008-01-05 01:18:20 +00005980 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5981 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005982 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005983 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005984 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005985 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005986
Dan Gohman81b28ce2008-09-16 18:46:06 +00005987 // If we have an icmp le or icmp ge instruction, turn it into the
5988 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5989 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005990 switch (I.getPredicate()) {
5991 default: break;
5992 case ICmpInst::ICMP_ULE:
5993 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005994 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005995 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005996 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005997 case ICmpInst::ICMP_SLE:
5998 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005999 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006000 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006001 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006002 case ICmpInst::ICMP_UGE:
6003 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006004 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006005 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006006 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006007 case ICmpInst::ICMP_SGE:
6008 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006009 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006010 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006011 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006012 }
6013
Chris Lattner183661e2008-07-11 05:40:05 +00006014 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006015 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006016 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006017 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6018 }
6019
6020 // See if we can fold the comparison based on range information we can get
6021 // by checking whether bits are known to be zero or one in the input.
6022 if (BitWidth != 0) {
6023 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6024 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6025
6026 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006027 isSignBit ? APInt::getSignBit(BitWidth)
6028 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006029 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006030 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006031 if (SimplifyDemandedBits(I.getOperandUse(1),
6032 APInt::getAllOnesValue(BitWidth),
6033 Op1KnownZero, Op1KnownOne, 0))
6034 return &I;
6035
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006036 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006037 // in. Compute the Min, Max and RHS values based on the known bits. For the
6038 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006039 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6040 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6041 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6042 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6043 Op0Min, Op0Max);
6044 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6045 Op1Min, Op1Max);
6046 } else {
6047 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6048 Op0Min, Op0Max);
6049 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6050 Op1Min, Op1Max);
6051 }
6052
Chris Lattner183661e2008-07-11 05:40:05 +00006053 // If Min and Max are known to be the same, then SimplifyDemandedBits
6054 // figured out that the LHS is a constant. Just constant fold this now so
6055 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006056 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006057 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006058 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006059 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006060 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006061 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006062
Chris Lattner183661e2008-07-11 05:40:05 +00006063 // Based on the range information we know about the LHS, see if we can
6064 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006065 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006066 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006067 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006068 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006069 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006070 break;
6071 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006072 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006073 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006074 break;
6075 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006076 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006077 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006078 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006079 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006080 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006081 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6083 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006084 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006085 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086
6087 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6088 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006089 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006090 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006091 }
Chris Lattner84dff672008-07-11 05:08:55 +00006092 break;
6093 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006095 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006097 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098
6099 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006100 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006101 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6102 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006103 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006104 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105
6106 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6107 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006108 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006109 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 }
Chris Lattner84dff672008-07-11 05:08:55 +00006111 break;
6112 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006114 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006116 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006118 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6120 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006121 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006122 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123 }
Chris Lattner84dff672008-07-11 05:08:55 +00006124 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 case ICmpInst::ICMP_SGT:
6126 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006127 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006129 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130
6131 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006132 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6134 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006135 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006136 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 }
6138 break;
6139 case ICmpInst::ICMP_SGE:
6140 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6141 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006142 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006144 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 break;
6146 case ICmpInst::ICMP_SLE:
6147 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6148 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006149 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006151 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 break;
6153 case ICmpInst::ICMP_UGE:
6154 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6155 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006156 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006157 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006158 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 break;
6160 case ICmpInst::ICMP_ULE:
6161 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6162 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006165 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006166 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006167 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168
6169 // Turn a signed comparison into an unsigned one if both operands
6170 // are known to have the same sign.
6171 if (I.isSignedPredicate() &&
6172 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6173 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006174 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006175 }
6176
6177 // Test if the ICmpInst instruction is used exclusively by a select as
6178 // part of a minimum or maximum operation. If so, refrain from doing
6179 // any other folding. This helps out other analyses which understand
6180 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6181 // and CodeGen. And in this case, at least one of the comparison
6182 // operands has at least one user besides the compare (the select),
6183 // which would often largely negate the benefit of folding anyway.
6184 if (I.hasOneUse())
6185 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6186 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6187 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6188 return 0;
6189
6190 // See if we are doing a comparison between a constant and an instruction that
6191 // can be folded into the comparison.
6192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006193 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006194 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006195 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006196 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006197 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6198 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006199 }
6200
Chris Lattner01deb9d2007-04-03 17:43:25 +00006201 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006202 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6203 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6204 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006205 case Instruction::GetElementPtr:
6206 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006207 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006208 bool isAllZeros = true;
6209 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6210 if (!isa<Constant>(LHSI->getOperand(i)) ||
6211 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6212 isAllZeros = false;
6213 break;
6214 }
6215 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006216 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006217 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006218 }
6219 break;
6220
Chris Lattner6970b662005-04-23 15:31:55 +00006221 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006222 // Only fold icmp into the PHI if the phi and fcmp are in the same
6223 // block. If in the same block, we're encouraging jump threading. If
6224 // not, we are just pessimizing the code by making an i1 phi.
6225 if (LHSI->getParent() == I.getParent())
6226 if (Instruction *NV = FoldOpIntoPhi(I))
6227 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006228 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006229 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006230 // If either operand of the select is a constant, we can fold the
6231 // comparison into the select arms, which will cause one to be
6232 // constant folded and the select turned into a bitwise or.
6233 Value *Op1 = 0, *Op2 = 0;
6234 if (LHSI->hasOneUse()) {
6235 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6236 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006237 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006238 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006239 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6240 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006241 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6242 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006243 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006244 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006245 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6246 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006247 }
6248 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006249
Chris Lattner6970b662005-04-23 15:31:55 +00006250 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006251 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006252 break;
6253 }
Chris Lattner4802d902007-04-06 18:57:34 +00006254 case Instruction::Malloc:
6255 // If we have (malloc != null), and if the malloc has a single use, we
6256 // can assume it is successful and remove the malloc.
6257 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006258 Worklist.Add(LHSI);
Victor Hernandez83d63912009-09-18 22:35:49 +00006259 return ReplaceInstUsesWith(I,
6260 ConstantInt::get(Type::getInt1Ty(*Context),
6261 !I.isTrueWhenEqual()));
6262 }
6263 break;
6264 case Instruction::Call:
6265 // If we have (malloc != null), and if the malloc has a single use, we
6266 // can assume it is successful and remove the malloc.
6267 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6268 isa<ConstantPointerNull>(RHSC)) {
6269 Worklist.Add(LHSI);
6270 return ReplaceInstUsesWith(I,
6271 ConstantInt::get(Type::getInt1Ty(*Context),
6272 !I.isTrueWhenEqual()));
6273 }
6274 break;
6275 case Instruction::BitCast:
6276 // If we have (malloc != null), and if the malloc has a single use, we
6277 // can assume it is successful and remove the malloc.
6278 CallInst* CI = extractMallocCallFromBitCast(LHSI);
6279 if (CI && CI->hasOneUse() && LHSI->hasOneUse()
6280 && isa<ConstantPointerNull>(RHSC)) {
6281 Worklist.Add(LHSI);
6282 Worklist.Add(CI);
6283 return ReplaceInstUsesWith(I,
6284 ConstantInt::get(Type::getInt1Ty(*Context),
6285 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006286 }
6287 break;
6288 }
Chris Lattner6970b662005-04-23 15:31:55 +00006289 }
6290
Reid Spencere4d87aa2006-12-23 06:05:41 +00006291 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006292 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006294 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006295 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006296 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6297 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006298 return NI;
6299
Reid Spencere4d87aa2006-12-23 06:05:41 +00006300 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006301 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6302 // now.
6303 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6304 if (isa<PointerType>(Op0->getType()) &&
6305 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006306 // We keep moving the cast from the left operand over to the right
6307 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006308 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006309
Chris Lattner57d86372007-01-06 01:45:59 +00006310 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6311 // so eliminate it as well.
6312 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6313 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006314
Chris Lattnerde90b762003-11-03 04:25:02 +00006315 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006316 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006317 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006318 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006319 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006320 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006321 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006322 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006323 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006324 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006325 }
Chris Lattner57d86372007-01-06 01:45:59 +00006326 }
6327
6328 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006329 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006330 // This comes up when you have code like
6331 // int X = A < B;
6332 // if (X) ...
6333 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006334 // with a constant or another cast from the same type.
6335 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006337 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006338 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006339
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006340 // See if it's the same type of instruction on the left and right.
6341 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6342 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006343 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006344 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006345 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006346 default: break;
6347 case Instruction::Add:
6348 case Instruction::Sub:
6349 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006350 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006351 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006352 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006353 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6354 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6355 if (CI->getValue().isSignBit()) {
6356 ICmpInst::Predicate Pred = I.isSignedPredicate()
6357 ? I.getUnsignedPredicate()
6358 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006359 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006360 Op1I->getOperand(0));
6361 }
6362
6363 if (CI->getValue().isMaxSignedValue()) {
6364 ICmpInst::Predicate Pred = I.isSignedPredicate()
6365 ? I.getUnsignedPredicate()
6366 : I.getSignedPredicate();
6367 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006368 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006369 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006370 }
6371 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006372 break;
6373 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006374 if (!I.isEquality())
6375 break;
6376
Nick Lewycky5d52c452008-08-21 05:56:10 +00006377 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6378 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6379 // Mask = -1 >> count-trailing-zeros(Cst).
6380 if (!CI->isZero() && !CI->isOne()) {
6381 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006382 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006383 APInt::getLowBitsSet(AP.getBitWidth(),
6384 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006385 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006386 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6387 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006388 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006389 }
6390 }
6391 break;
6392 }
6393 }
6394 }
6395 }
6396
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006397 // ~x < ~y --> y < x
6398 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006399 if (match(Op0, m_Not(m_Value(A))) &&
6400 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006401 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006402 }
6403
Chris Lattner65b72ba2006-09-18 04:22:48 +00006404 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006405 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006406
6407 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006408 if (match(Op0, m_Neg(m_Value(A))) &&
6409 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006410 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006411
Dan Gohman4ae51262009-08-12 16:23:25 +00006412 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006413 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6414 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006415 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006416 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006417 }
6418
Dan Gohman4ae51262009-08-12 16:23:25 +00006419 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006420 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006421 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006422 if (match(B, m_ConstantInt(C1)) &&
6423 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006424 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006425 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006426 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6427 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006428 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006429
6430 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006431 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6432 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6433 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6434 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006435 }
6436 }
6437
Dan Gohman4ae51262009-08-12 16:23:25 +00006438 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006439 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006440 // A == (A^B) -> B == 0
6441 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006442 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006443 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006444 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006445
6446 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006447 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006448 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006449 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006450
6451 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006452 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006453 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006454 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006455
Chris Lattner9c2328e2006-11-14 06:06:06 +00006456 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6457 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006458 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6459 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006460 Value *X = 0, *Y = 0, *Z = 0;
6461
6462 if (A == C) {
6463 X = B; Y = D; Z = A;
6464 } else if (A == D) {
6465 X = B; Y = C; Z = A;
6466 } else if (B == C) {
6467 X = A; Y = D; Z = B;
6468 } else if (B == D) {
6469 X = A; Y = C; Z = B;
6470 }
6471
6472 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006473 Op1 = Builder->CreateXor(X, Y, "tmp");
6474 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006475 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006476 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006477 return &I;
6478 }
6479 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006480 }
Chris Lattner7e708292002-06-25 16:13:24 +00006481 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006482}
6483
Chris Lattner562ef782007-06-20 23:46:26 +00006484
6485/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6486/// and CmpRHS are both known to be integer constants.
6487Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6488 ConstantInt *DivRHS) {
6489 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6490 const APInt &CmpRHSV = CmpRHS->getValue();
6491
6492 // FIXME: If the operand types don't match the type of the divide
6493 // then don't attempt this transform. The code below doesn't have the
6494 // logic to deal with a signed divide and an unsigned compare (and
6495 // vice versa). This is because (x /s C1) <s C2 produces different
6496 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6497 // (x /u C1) <u C2. Simply casting the operands and result won't
6498 // work. :( The if statement below tests that condition and bails
6499 // if it finds it.
6500 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6501 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6502 return 0;
6503 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006504 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006505 if (DivIsSigned && DivRHS->isAllOnesValue())
6506 return 0; // The overflow computation also screws up here
6507 if (DivRHS->isOne())
6508 return 0; // Not worth bothering, and eliminates some funny cases
6509 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006510
6511 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6512 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6513 // C2 (CI). By solving for X we can turn this into a range check
6514 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006515 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006516
6517 // Determine if the product overflows by seeing if the product is
6518 // not equal to the divide. Make sure we do the same kind of divide
6519 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006520 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6521 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006522
6523 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006524 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006525
Chris Lattner1dbfd482007-06-21 18:11:19 +00006526 // Figure out the interval that is being checked. For example, a comparison
6527 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6528 // Compute this interval based on the constants involved and the signedness of
6529 // the compare/divide. This computes a half-open interval, keeping track of
6530 // whether either value in the interval overflows. After analysis each
6531 // overflow variable is set to 0 if it's corresponding bound variable is valid
6532 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6533 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006534 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006535
Chris Lattner562ef782007-06-20 23:46:26 +00006536 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006537 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006538 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006539 HiOverflow = LoOverflow = ProdOV;
6540 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006541 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006542 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006543 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006544 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006545 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006546 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006547 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006548 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6549 HiOverflow = LoOverflow = ProdOV;
6550 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006551 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006552 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006553 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006554 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006555 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6556 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006557 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006558 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006559 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006560 true) ? -1 : 0;
6561 }
Chris Lattner562ef782007-06-20 23:46:26 +00006562 }
Dan Gohman76491272008-02-13 22:09:18 +00006563 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006564 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006565 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006566 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006567 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006568 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6569 HiOverflow = 1; // [INTMIN+1, overflow)
6570 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6571 }
Dan Gohman76491272008-02-13 22:09:18 +00006572 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006574 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006575 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006576 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006577 LoOverflow = AddWithOverflow(LoBound, HiBound,
6578 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006579 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006580 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6581 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006582 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006583 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006584 }
6585
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 // Dividing by a negative swaps the condition. LT <-> GT
6587 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006588 }
6589
6590 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006592 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006593 case ICmpInst::ICMP_EQ:
6594 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006595 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006596 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006597 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006598 ICmpInst::ICMP_UGE, X, LoBound);
6599 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006600 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006601 ICmpInst::ICMP_ULT, X, HiBound);
6602 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006604 case ICmpInst::ICMP_NE:
6605 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006606 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006607 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006608 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006609 ICmpInst::ICMP_ULT, X, LoBound);
6610 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006611 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006612 ICmpInst::ICMP_UGE, X, HiBound);
6613 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006614 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006615 case ICmpInst::ICMP_ULT:
6616 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006617 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006618 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006620 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006621 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006622 case ICmpInst::ICMP_UGT:
6623 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006625 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006626 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006627 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006628 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006629 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006630 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006631 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006632 }
6633}
6634
6635
Chris Lattner01deb9d2007-04-03 17:43:25 +00006636/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6637///
6638Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6639 Instruction *LHSI,
6640 ConstantInt *RHS) {
6641 const APInt &RHSV = RHS->getValue();
6642
6643 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006644 case Instruction::Trunc:
6645 if (ICI.isEquality() && LHSI->hasOneUse()) {
6646 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6647 // of the high bits truncated out of x are known.
6648 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6649 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6650 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6651 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6652 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6653
6654 // If all the high bits are known, we can do this xform.
6655 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6656 // Pull in the high bits from known-ones set.
6657 APInt NewRHS(RHS->getValue());
6658 NewRHS.zext(SrcBits);
6659 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006660 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006661 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006662 }
6663 }
6664 break;
6665
Duncan Sands0091bf22007-04-04 06:42:45 +00006666 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006667 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6668 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6669 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006670 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6671 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006672 Value *CompareVal = LHSI->getOperand(0);
6673
6674 // If the sign bit of the XorCST is not set, there is no change to
6675 // the operation, just stop using the Xor.
6676 if (!XorCST->getValue().isNegative()) {
6677 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006678 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006679 return &ICI;
6680 }
6681
6682 // Was the old condition true if the operand is positive?
6683 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6684
6685 // If so, the new one isn't.
6686 isTrueIfPositive ^= true;
6687
6688 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006689 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006690 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006691 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006692 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006693 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006694 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006695
6696 if (LHSI->hasOneUse()) {
6697 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6698 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6699 const APInt &SignBit = XorCST->getValue();
6700 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6701 ? ICI.getUnsignedPredicate()
6702 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006703 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006704 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006705 }
6706
6707 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006708 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006709 const APInt &NotSignBit = XorCST->getValue();
6710 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6711 ? ICI.getUnsignedPredicate()
6712 : ICI.getSignedPredicate();
6713 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006714 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006715 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006716 }
6717 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006718 }
6719 break;
6720 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6721 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6722 LHSI->getOperand(0)->hasOneUse()) {
6723 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6724
6725 // If the LHS is an AND of a truncating cast, we can widen the
6726 // and/compare to be the input width without changing the value
6727 // produced, eliminating a cast.
6728 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6729 // We can do this transformation if either the AND constant does not
6730 // have its sign bit set or if it is an equality comparison.
6731 // Extending a relational comparison when we're checking the sign
6732 // bit would not work.
6733 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006734 (ICI.isEquality() ||
6735 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006736 uint32_t BitWidth =
6737 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6738 APInt NewCST = AndCST->getValue();
6739 NewCST.zext(BitWidth);
6740 APInt NewCI = RHSV;
6741 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006742 Value *NewAnd =
6743 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006744 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006745 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006746 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006747 }
6748 }
6749
6750 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6751 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6752 // happens a LOT in code produced by the C front-end, for bitfield
6753 // access.
6754 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6755 if (Shift && !Shift->isShift())
6756 Shift = 0;
6757
6758 ConstantInt *ShAmt;
6759 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6760 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6761 const Type *AndTy = AndCST->getType(); // Type of the and.
6762
6763 // We can fold this as long as we can't shift unknown bits
6764 // into the mask. This can only happen with signed shift
6765 // rights, as they sign-extend.
6766 if (ShAmt) {
6767 bool CanFold = Shift->isLogicalShift();
6768 if (!CanFold) {
6769 // To test for the bad case of the signed shr, see if any
6770 // of the bits shifted in could be tested after the mask.
6771 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6772 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6773
6774 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6775 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6776 AndCST->getValue()) == 0)
6777 CanFold = true;
6778 }
6779
6780 if (CanFold) {
6781 Constant *NewCst;
6782 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006783 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006784 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006785 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006786
6787 // Check to see if we are shifting out any of the bits being
6788 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006789 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006790 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006791 // If we shifted bits out, the fold is not going to work out.
6792 // As a special case, check to see if this means that the
6793 // result is always true or false now.
6794 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006795 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006797 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006798 } else {
6799 ICI.setOperand(1, NewCst);
6800 Constant *NewAndCST;
6801 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006802 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006803 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006804 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006805 LHSI->setOperand(1, NewAndCST);
6806 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006807 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006808 return &ICI;
6809 }
6810 }
6811 }
6812
6813 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6814 // preferable because it allows the C<<Y expression to be hoisted out
6815 // of a loop if Y is invariant and X is not.
6816 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006817 ICI.isEquality() && !Shift->isArithmeticShift() &&
6818 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006819 // Compute C << Y.
6820 Value *NS;
6821 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006822 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006823 } else {
6824 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006825 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006826 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006827
6828 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006829 Value *NewAnd =
6830 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006831
6832 ICI.setOperand(0, NewAnd);
6833 return &ICI;
6834 }
6835 }
6836 break;
6837
Chris Lattnera0141b92007-07-15 20:42:37 +00006838 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6839 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6840 if (!ShAmt) break;
6841
6842 uint32_t TypeBits = RHSV.getBitWidth();
6843
6844 // Check that the shift amount is in range. If not, don't perform
6845 // undefined shifts. When the shift is visited it will be
6846 // simplified.
6847 if (ShAmt->uge(TypeBits))
6848 break;
6849
6850 if (ICI.isEquality()) {
6851 // If we are comparing against bits always shifted out, the
6852 // comparison cannot succeed.
6853 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006854 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006855 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006856 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6857 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006858 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006859 return ReplaceInstUsesWith(ICI, Cst);
6860 }
6861
6862 if (LHSI->hasOneUse()) {
6863 // Otherwise strength reduce the shift into an and.
6864 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6865 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006866 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006867 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006868
Chris Lattner74381062009-08-30 07:44:24 +00006869 Value *And =
6870 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006871 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006872 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873 }
6874 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006875
6876 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6877 bool TrueIfSigned = false;
6878 if (LHSI->hasOneUse() &&
6879 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6880 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006881 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006882 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006883 Value *And =
6884 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006885 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006886 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006887 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006888 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006889 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006890
6891 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006892 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006893 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006894 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006895 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006896
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006897 // Check that the shift amount is in range. If not, don't perform
6898 // undefined shifts. When the shift is visited it will be
6899 // simplified.
6900 uint32_t TypeBits = RHSV.getBitWidth();
6901 if (ShAmt->uge(TypeBits))
6902 break;
6903
6904 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006905
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006906 // If we are comparing against bits always shifted out, the
6907 // comparison cannot succeed.
6908 APInt Comp = RHSV << ShAmtVal;
6909 if (LHSI->getOpcode() == Instruction::LShr)
6910 Comp = Comp.lshr(ShAmtVal);
6911 else
6912 Comp = Comp.ashr(ShAmtVal);
6913
6914 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6915 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006916 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006917 return ReplaceInstUsesWith(ICI, Cst);
6918 }
6919
6920 // Otherwise, check to see if the bits shifted out are known to be zero.
6921 // If so, we can compare against the unshifted value:
6922 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006923 if (LHSI->hasOneUse() &&
6924 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006925 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006926 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006927 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006928 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006929
Evan Chengf30752c2008-04-23 00:38:06 +00006930 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006931 // Otherwise strength reduce the shift into an and.
6932 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006933 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006934
Chris Lattner74381062009-08-30 07:44:24 +00006935 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6936 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006937 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006938 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006939 }
6940 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006942
6943 case Instruction::SDiv:
6944 case Instruction::UDiv:
6945 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6946 // Fold this div into the comparison, producing a range check.
6947 // Determine, based on the divide type, what the range is being
6948 // checked. If there is an overflow on the low or high side, remember
6949 // it, otherwise compute the range [low, hi) bounding the new value.
6950 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006951 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6952 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6953 DivRHS))
6954 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006955 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006956
6957 case Instruction::Add:
6958 // Fold: icmp pred (add, X, C1), C2
6959
6960 if (!ICI.isEquality()) {
6961 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6962 if (!LHSC) break;
6963 const APInt &LHSV = LHSC->getValue();
6964
6965 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6966 .subtract(LHSV);
6967
6968 if (ICI.isSignedPredicate()) {
6969 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006970 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006971 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006972 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006973 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006974 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006975 }
6976 } else {
6977 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006978 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006979 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006980 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006981 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006982 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006983 }
6984 }
6985 }
6986 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006987 }
6988
6989 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6990 if (ICI.isEquality()) {
6991 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6992
6993 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6994 // the second operand is a constant, simplify a bit.
6995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6996 switch (BO->getOpcode()) {
6997 case Instruction::SRem:
6998 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6999 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7000 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7001 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007002 Value *NewRem =
7003 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7004 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007005 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007006 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007007 }
7008 }
7009 break;
7010 case Instruction::Add:
7011 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7012 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7013 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007014 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007015 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007016 } else if (RHSV == 0) {
7017 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7018 // efficiently invertible, or if the add has just this one use.
7019 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7020
Dan Gohman186a6362009-08-12 16:04:34 +00007021 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007022 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007023 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007024 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007025 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007026 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007027 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007028 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007029 }
7030 }
7031 break;
7032 case Instruction::Xor:
7033 // For the xor case, we can xor two constants together, eliminating
7034 // the explicit xor.
7035 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007036 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007037 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038
7039 // FALLTHROUGH
7040 case Instruction::Sub:
7041 // Replace (([sub|xor] A, B) != 0) with (A != B)
7042 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007043 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007044 BO->getOperand(1));
7045 break;
7046
7047 case Instruction::Or:
7048 // If bits are being or'd in that are not present in the constant we
7049 // are comparing against, then the comparison could never succeed!
7050 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007051 Constant *NotCI = ConstantExpr::getNot(RHS);
7052 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007053 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007054 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007055 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007056 }
7057 break;
7058
7059 case Instruction::And:
7060 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7061 // If bits are being compared against that are and'd out, then the
7062 // comparison can never succeed!
7063 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007064 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007065 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007066 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067
7068 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7069 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007070 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007071 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007072 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007073
7074 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007075 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007076 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007077 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078 ICmpInst::Predicate pred = isICMP_NE ?
7079 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007080 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081 }
7082
7083 // ((X & ~7) == 0) --> X < 8
7084 if (RHSV == 0 && isHighOnes(BOC)) {
7085 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007086 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007087 ICmpInst::Predicate pred = isICMP_NE ?
7088 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007089 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090 }
7091 }
7092 default: break;
7093 }
7094 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7095 // Handle icmp {eq|ne} <intrinsic>, intcst.
7096 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007097 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007098 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007099 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007100 return &ICI;
7101 }
7102 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007103 }
7104 return 0;
7105}
7106
7107/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7108/// We only handle extending casts so far.
7109///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007110Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7111 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007112 Value *LHSCIOp = LHSCI->getOperand(0);
7113 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007114 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007115 Value *RHSCIOp;
7116
Chris Lattner8c756c12007-05-05 22:41:33 +00007117 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7118 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007119 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7120 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007121 cast<IntegerType>(DestTy)->getBitWidth()) {
7122 Value *RHSOp = 0;
7123 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007124 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007125 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7126 RHSOp = RHSC->getOperand(0);
7127 // If the pointer types don't match, insert a bitcast.
7128 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007129 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007130 }
7131
7132 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007133 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007134 }
7135
7136 // The code below only handles extension cast instructions, so far.
7137 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007138 if (LHSCI->getOpcode() != Instruction::ZExt &&
7139 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007140 return 0;
7141
Reid Spencere4d87aa2006-12-23 06:05:41 +00007142 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7143 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007144
Reid Spencere4d87aa2006-12-23 06:05:41 +00007145 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007146 // Not an extension from the same type?
7147 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007148 if (RHSCIOp->getType() != LHSCIOp->getType())
7149 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007150
Nick Lewycky4189a532008-01-28 03:48:02 +00007151 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007152 // and the other is a zext), then we can't handle this.
7153 if (CI->getOpcode() != LHSCI->getOpcode())
7154 return 0;
7155
Nick Lewycky4189a532008-01-28 03:48:02 +00007156 // Deal with equality cases early.
7157 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007158 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007159
7160 // A signed comparison of sign extended values simplifies into a
7161 // signed comparison.
7162 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007163 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007164
7165 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007166 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007167 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007168
Reid Spencere4d87aa2006-12-23 06:05:41 +00007169 // If we aren't dealing with a constant on the RHS, exit early
7170 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7171 if (!CI)
7172 return 0;
7173
7174 // Compute the constant that would happen if we truncated to SrcTy then
7175 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007176 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7177 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007178 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007179
7180 // If the re-extended constant didn't change...
7181 if (Res2 == CI) {
7182 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7183 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007184 // %A = sext i16 %X to i32
7185 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007186 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007187 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007188 // because %A may have negative value.
7189 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007190 // However, we allow this when the compare is EQ/NE, because they are
7191 // signless.
7192 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007193 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007194 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007195 }
7196
7197 // The re-extended constant changed so the constant cannot be represented
7198 // in the shorter type. Consequently, we cannot emit a simple comparison.
7199
7200 // First, handle some easy cases. We know the result cannot be equal at this
7201 // point so handle the ICI.isEquality() cases
7202 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007203 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007204 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007205 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007206
7207 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7208 // should have been folded away previously and not enter in here.
7209 Value *Result;
7210 if (isSignedCmp) {
7211 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007212 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007213 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007214 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007215 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007216 } else {
7217 // We're performing an unsigned comparison.
7218 if (isSignedExt) {
7219 // We're performing an unsigned comp with a sign extended value.
7220 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007221 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007222 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007223 } else {
7224 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007225 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007226 }
7227 }
7228
7229 // Finally, return the value computed.
7230 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007231 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007233
7234 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7235 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7236 "ICmp should be folded!");
7237 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007238 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007239 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007240}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007241
Reid Spencer832254e2007-02-02 02:16:23 +00007242Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7243 return commonShiftTransforms(I);
7244}
7245
7246Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7247 return commonShiftTransforms(I);
7248}
7249
7250Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007251 if (Instruction *R = commonShiftTransforms(I))
7252 return R;
7253
7254 Value *Op0 = I.getOperand(0);
7255
7256 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7257 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7258 if (CSI->isAllOnesValue())
7259 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007260
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007261 // See if we can turn a signed shr into an unsigned shr.
7262 if (MaskedValueIsZero(Op0,
7263 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7264 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7265
7266 // Arithmetic shifting an all-sign-bit value is a no-op.
7267 unsigned NumSignBits = ComputeNumSignBits(Op0);
7268 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7269 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007270
Chris Lattner348f6652007-12-06 01:59:46 +00007271 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007272}
7273
7274Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7275 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007276 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007277
7278 // shl X, 0 == X and shr X, 0 == X
7279 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007280 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7281 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007282 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007283
Reid Spencere4d87aa2006-12-23 06:05:41 +00007284 if (isa<UndefValue>(Op0)) {
7285 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007286 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007288 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007289 }
7290 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007291 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7292 return ReplaceInstUsesWith(I, Op0);
7293 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007295 }
7296
Dan Gohman9004c8a2009-05-21 02:28:33 +00007297 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007298 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007299 return &I;
7300
Chris Lattner2eefe512004-04-09 19:05:30 +00007301 // Try to fold constant and into select arguments.
7302 if (isa<Constant>(Op0))
7303 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007304 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007305 return R;
7306
Reid Spencerb83eb642006-10-20 07:07:24 +00007307 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007308 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7309 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007310 return 0;
7311}
7312
Reid Spencerb83eb642006-10-20 07:07:24 +00007313Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007314 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007315 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007316
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007317 // See if we can simplify any instructions used by the instruction whose sole
7318 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007319 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007320
Dan Gohmana119de82009-06-14 23:30:43 +00007321 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7322 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007323 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007324 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007325 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007326 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007327 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007328 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007329 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007330 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007331 }
7332
7333 // ((X*C1) << C2) == (X * (C1 << C2))
7334 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7335 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7336 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007337 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007338 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007339
7340 // Try to fold constant and into select arguments.
7341 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7342 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7343 return R;
7344 if (isa<PHINode>(Op0))
7345 if (Instruction *NV = FoldOpIntoPhi(I))
7346 return NV;
7347
Chris Lattner8999dd32007-12-22 09:07:47 +00007348 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7349 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7350 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7351 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7352 // place. Don't try to do this transformation in this case. Also, we
7353 // require that the input operand is a shift-by-constant so that we have
7354 // confidence that the shifts will get folded together. We could do this
7355 // xform in more cases, but it is unlikely to be profitable.
7356 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7357 isa<ConstantInt>(TrOp->getOperand(1))) {
7358 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007359 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007360 // (shift2 (shift1 & 0x00FF), c2)
7361 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007362
7363 // For logical shifts, the truncation has the effect of making the high
7364 // part of the register be zeros. Emulate this by inserting an AND to
7365 // clear the top bits as needed. This 'and' will usually be zapped by
7366 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007367 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7368 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007369 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7370
7371 // The mask we constructed says what the trunc would do if occurring
7372 // between the shifts. We want to know the effect *after* the second
7373 // shift. We know that it is a logical shift by a constant, so adjust the
7374 // mask as appropriate.
7375 if (I.getOpcode() == Instruction::Shl)
7376 MaskV <<= Op1->getZExtValue();
7377 else {
7378 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7379 MaskV = MaskV.lshr(Op1->getZExtValue());
7380 }
7381
Chris Lattner74381062009-08-30 07:44:24 +00007382 // shift1 & 0x00FF
7383 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7384 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007385
7386 // Return the value truncated to the interesting size.
7387 return new TruncInst(And, I.getType());
7388 }
7389 }
7390
Chris Lattner4d5542c2006-01-06 07:12:35 +00007391 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007392 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7393 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7394 Value *V1, *V2;
7395 ConstantInt *CC;
7396 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007397 default: break;
7398 case Instruction::Add:
7399 case Instruction::And:
7400 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007401 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007402 // These operators commute.
7403 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007404 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007405 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007406 m_Specific(Op1)))) {
7407 Value *YS = // (Y << C)
7408 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7409 // (X + (Y << C))
7410 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7411 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007412 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007413 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007414 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007415 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007416
Chris Lattner150f12a2005-09-18 06:30:59 +00007417 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007418 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007419 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007420 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007421 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007422 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007423 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007424 Value *YS = // (Y << C)
7425 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7426 Op0BO->getName());
7427 // X & (CC << C)
7428 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7429 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007430 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007431 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007432 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007433
Reid Spencera07cb7d2007-02-02 14:41:37 +00007434 // FALL THROUGH.
7435 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007436 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007437 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007438 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007439 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007440 Value *YS = // (Y << C)
7441 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7442 // (X + (Y << C))
7443 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7444 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007445 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007446 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007447 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007448 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007449
Chris Lattner13d4ab42006-05-31 21:14:00 +00007450 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007451 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7452 match(Op0BO->getOperand(0),
7453 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007454 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007455 cast<BinaryOperator>(Op0BO->getOperand(0))
7456 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007457 Value *YS = // (Y << C)
7458 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7459 // X & (CC << C)
7460 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7461 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007462
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007463 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007464 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007465
Chris Lattner11021cb2005-09-18 05:12:10 +00007466 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007467 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007468 }
7469
7470
7471 // If the operand is an bitwise operator with a constant RHS, and the
7472 // shift is the only use, we can pull it out of the shift.
7473 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7474 bool isValid = true; // Valid only for And, Or, Xor
7475 bool highBitSet = false; // Transform if high bit of constant set?
7476
7477 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007478 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007479 case Instruction::Add:
7480 isValid = isLeftShift;
7481 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007482 case Instruction::Or:
7483 case Instruction::Xor:
7484 highBitSet = false;
7485 break;
7486 case Instruction::And:
7487 highBitSet = true;
7488 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007489 }
7490
7491 // If this is a signed shift right, and the high bit is modified
7492 // by the logical operation, do not perform the transformation.
7493 // The highBitSet boolean indicates the value of the high bit of
7494 // the constant which would cause it to be modified for this
7495 // operation.
7496 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007497 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007498 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007499
7500 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007501 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007502
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007503 Value *NewShift =
7504 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007505 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007506
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007507 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007508 NewRHS);
7509 }
7510 }
7511 }
7512 }
7513
Chris Lattnerad0124c2006-01-06 07:52:12 +00007514 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007515 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7516 if (ShiftOp && !ShiftOp->isShift())
7517 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007518
Reid Spencerb83eb642006-10-20 07:07:24 +00007519 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007520 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007521 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7522 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007523 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7524 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7525 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007526
Zhou Sheng4351c642007-04-02 08:20:41 +00007527 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007528
7529 const IntegerType *Ty = cast<IntegerType>(I.getType());
7530
7531 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007532 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007533 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7534 // saturates.
7535 if (AmtSum >= TypeBits) {
7536 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007537 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007538 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7539 }
7540
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007541 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007542 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007543 }
7544
7545 if (ShiftOp->getOpcode() == Instruction::LShr &&
7546 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007547 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007548 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007549
Chris Lattnerb87056f2007-02-05 00:57:54 +00007550 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007551 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007552 }
7553
7554 if (ShiftOp->getOpcode() == Instruction::AShr &&
7555 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007556 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007557 if (AmtSum >= TypeBits)
7558 AmtSum = TypeBits-1;
7559
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007560 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007561
Zhou Shenge9e03f62007-03-28 15:02:20 +00007562 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007563 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007564 }
7565
Chris Lattnerb87056f2007-02-05 00:57:54 +00007566 // Okay, if we get here, one shift must be left, and the other shift must be
7567 // right. See if the amounts are equal.
7568 if (ShiftAmt1 == ShiftAmt2) {
7569 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7570 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007571 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007572 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007573 }
7574 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7575 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007576 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007577 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007578 }
7579 // We can simplify ((X << C) >>s C) into a trunc + sext.
7580 // NOTE: we could do this for any C, but that would make 'unusual' integer
7581 // types. For now, just stick to ones well-supported by the code
7582 // generators.
7583 const Type *SExtType = 0;
7584 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007585 case 1 :
7586 case 8 :
7587 case 16 :
7588 case 32 :
7589 case 64 :
7590 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007591 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007592 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007593 default: break;
7594 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007595 if (SExtType)
7596 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007597 // Otherwise, we can't handle it yet.
7598 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007599 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007600
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007601 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007602 if (I.getOpcode() == Instruction::Shl) {
7603 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7604 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007605 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007606
Reid Spencer55702aa2007-03-25 21:11:44 +00007607 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007608 return BinaryOperator::CreateAnd(Shift,
7609 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007610 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007611
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007612 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613 if (I.getOpcode() == Instruction::LShr) {
7614 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007615 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007616
Reid Spencerd5e30f02007-03-26 17:18:58 +00007617 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007618 return BinaryOperator::CreateAnd(Shift,
7619 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007620 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007621
7622 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7623 } else {
7624 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007625 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007627 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628 if (I.getOpcode() == Instruction::Shl) {
7629 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7630 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007631 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7632 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633
Reid Spencer55702aa2007-03-25 21:11:44 +00007634 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007635 return BinaryOperator::CreateAnd(Shift,
7636 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007637 }
7638
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007639 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007640 if (I.getOpcode() == Instruction::LShr) {
7641 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007642 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007643
Reid Spencer68d27cf2007-03-26 23:45:51 +00007644 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007645 return BinaryOperator::CreateAnd(Shift,
7646 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647 }
7648
7649 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007650 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007651 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007652 return 0;
7653}
7654
Chris Lattnera1be5662002-05-02 17:06:02 +00007655
Chris Lattnercfd65102005-10-29 04:36:15 +00007656/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7657/// expression. If so, decompose it, returning some value X, such that Val is
7658/// X*Scale+Offset.
7659///
7660static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007661 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007662 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7663 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007664 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007665 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007666 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007667 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007668 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7669 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7670 if (I->getOpcode() == Instruction::Shl) {
7671 // This is a value scaled by '1 << the shift amt'.
7672 Scale = 1U << RHS->getZExtValue();
7673 Offset = 0;
7674 return I->getOperand(0);
7675 } else if (I->getOpcode() == Instruction::Mul) {
7676 // This value is scaled by 'RHS'.
7677 Scale = RHS->getZExtValue();
7678 Offset = 0;
7679 return I->getOperand(0);
7680 } else if (I->getOpcode() == Instruction::Add) {
7681 // We have X+C. Check to see if we really have (X*C2)+C1,
7682 // where C1 is divisible by C2.
7683 unsigned SubScale;
7684 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007685 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7686 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007687 Offset += RHS->getZExtValue();
7688 Scale = SubScale;
7689 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007690 }
7691 }
7692 }
7693
7694 // Otherwise, we can't look past this.
7695 Scale = 1;
7696 Offset = 0;
7697 return Val;
7698}
7699
7700
Chris Lattnerb3f83972005-10-24 06:03:58 +00007701/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7702/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007703Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007704 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007705 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007706
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007707 BuilderTy AllocaBuilder(*Builder);
7708 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7709
Chris Lattnerb53c2382005-10-24 06:22:12 +00007710 // Remove any uses of AI that are dead.
7711 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007712
Chris Lattnerb53c2382005-10-24 06:22:12 +00007713 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7714 Instruction *User = cast<Instruction>(*UI++);
7715 if (isInstructionTriviallyDead(User)) {
7716 while (UI != E && *UI == User)
7717 ++UI; // If this instruction uses AI more than once, don't break UI.
7718
Chris Lattnerb53c2382005-10-24 06:22:12 +00007719 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007720 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007721 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007722 }
7723 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007724
7725 // This requires TargetData to get the alloca alignment and size information.
7726 if (!TD) return 0;
7727
Chris Lattnerb3f83972005-10-24 06:03:58 +00007728 // Get the type really allocated and the type casted to.
7729 const Type *AllocElTy = AI.getAllocatedType();
7730 const Type *CastElTy = PTy->getElementType();
7731 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007732
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007733 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7734 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007735 if (CastElTyAlign < AllocElTyAlign) return 0;
7736
Chris Lattner39387a52005-10-24 06:35:18 +00007737 // If the allocation has multiple uses, only promote it if we are strictly
7738 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007739 // same, we open the door to infinite loops of various kinds. (A reference
7740 // from a dbg.declare doesn't count as a use for this purpose.)
7741 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7742 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007743
Duncan Sands777d2302009-05-09 07:06:46 +00007744 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7745 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007746 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007747
Chris Lattner455fcc82005-10-29 03:19:53 +00007748 // See if we can satisfy the modulus by pulling a scale out of the array
7749 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007750 unsigned ArraySizeScale;
7751 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007752 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007753 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7754 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007755
Chris Lattner455fcc82005-10-29 03:19:53 +00007756 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7757 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007758 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7759 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007760
Chris Lattner455fcc82005-10-29 03:19:53 +00007761 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7762 Value *Amt = 0;
7763 if (Scale == 1) {
7764 Amt = NumElements;
7765 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007766 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007767 // Insert before the alloca, not before the cast.
7768 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007769 }
7770
Jeff Cohen86796be2007-04-04 16:58:57 +00007771 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007772 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007773 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007774 }
7775
Chris Lattnerb3f83972005-10-24 06:03:58 +00007776 AllocationInst *New;
7777 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007778 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007779 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007780 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7781 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007782 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007783
Dale Johannesena0a66372009-03-05 00:39:02 +00007784 // If the allocation has one real use plus a dbg.declare, just remove the
7785 // declare.
7786 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7787 EraseInstFromFunction(*DI);
7788 }
7789 // If the allocation has multiple real uses, insert a cast and change all
7790 // things that used it to use the new cast. This will also hack on CI, but it
7791 // will die soon.
7792 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007793 // New is the allocation instruction, pointer typed. AI is the original
7794 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007795 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007796 AI.replaceAllUsesWith(NewCast);
7797 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007798 return ReplaceInstUsesWith(CI, New);
7799}
7800
Chris Lattner70074e02006-05-13 02:06:03 +00007801/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007802/// and return it as type Ty without inserting any new casts and without
7803/// changing the computed value. This is used by code that tries to decide
7804/// whether promoting or shrinking integer operations to wider or smaller types
7805/// will allow us to eliminate a truncate or extend.
7806///
7807/// This is a truncation operation if Ty is smaller than V->getType(), or an
7808/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007809///
7810/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7811/// should return true if trunc(V) can be computed by computing V in the smaller
7812/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7813/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7814/// efficiently truncated.
7815///
7816/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7817/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7818/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007819bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007820 unsigned CastOpc,
7821 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007822 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007823 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007824 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007825
7826 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007827 if (!I) return false;
7828
Dan Gohman6de29f82009-06-15 22:12:54 +00007829 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007830
Chris Lattner951626b2007-08-02 06:11:14 +00007831 // If this is an extension or truncate, we can often eliminate it.
7832 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7833 // If this is a cast from the destination type, we can trivially eliminate
7834 // it, and this will remove a cast overall.
7835 if (I->getOperand(0)->getType() == Ty) {
7836 // If the first operand is itself a cast, and is eliminable, do not count
7837 // this as an eliminable cast. We would prefer to eliminate those two
7838 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007839 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007840 ++NumCastsRemoved;
7841 return true;
7842 }
7843 }
7844
7845 // We can't extend or shrink something that has multiple uses: doing so would
7846 // require duplicating the instruction in general, which isn't profitable.
7847 if (!I->hasOneUse()) return false;
7848
Evan Chengf35fd542009-01-15 17:01:23 +00007849 unsigned Opc = I->getOpcode();
7850 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007851 case Instruction::Add:
7852 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007853 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007854 case Instruction::And:
7855 case Instruction::Or:
7856 case Instruction::Xor:
7857 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007858 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007859 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007860 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007861 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007862
Eli Friedman070a9812009-07-13 22:46:01 +00007863 case Instruction::UDiv:
7864 case Instruction::URem: {
7865 // UDiv and URem can be truncated if all the truncated bits are zero.
7866 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7867 uint32_t BitWidth = Ty->getScalarSizeInBits();
7868 if (BitWidth < OrigBitWidth) {
7869 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7870 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7871 MaskedValueIsZero(I->getOperand(1), Mask)) {
7872 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7873 NumCastsRemoved) &&
7874 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7875 NumCastsRemoved);
7876 }
7877 }
7878 break;
7879 }
Chris Lattner46b96052006-11-29 07:18:39 +00007880 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007881 // If we are truncating the result of this SHL, and if it's a shift of a
7882 // constant amount, we can always perform a SHL in a smaller type.
7883 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007884 uint32_t BitWidth = Ty->getScalarSizeInBits();
7885 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007886 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007887 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007888 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007889 }
7890 break;
7891 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007892 // If this is a truncate of a logical shr, we can truncate it to a smaller
7893 // lshr iff we know that the bits we would otherwise be shifting in are
7894 // already zeros.
7895 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007896 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7897 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007898 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007899 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007900 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7901 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007902 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007903 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007904 }
7905 }
Chris Lattner46b96052006-11-29 07:18:39 +00007906 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007907 case Instruction::ZExt:
7908 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007909 case Instruction::Trunc:
7910 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007911 // can safely replace it. Note that replacing it does not reduce the number
7912 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007913 if (Opc == CastOpc)
7914 return true;
7915
7916 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007917 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007918 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007919 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007920 case Instruction::Select: {
7921 SelectInst *SI = cast<SelectInst>(I);
7922 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007923 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007924 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007925 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007926 }
Chris Lattner8114b712008-06-18 04:00:49 +00007927 case Instruction::PHI: {
7928 // We can change a phi if we can change all operands.
7929 PHINode *PN = cast<PHINode>(I);
7930 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7931 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007932 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007933 return false;
7934 return true;
7935 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007936 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007937 // TODO: Can handle more cases here.
7938 break;
7939 }
7940
7941 return false;
7942}
7943
7944/// EvaluateInDifferentType - Given an expression that
7945/// CanEvaluateInDifferentType returns true for, actually insert the code to
7946/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007947Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007948 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007949 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007950 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007951 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007952
7953 // Otherwise, it must be an instruction.
7954 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007955 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007956 unsigned Opc = I->getOpcode();
7957 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007958 case Instruction::Add:
7959 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007960 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007961 case Instruction::And:
7962 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007963 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007964 case Instruction::AShr:
7965 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007966 case Instruction::Shl:
7967 case Instruction::UDiv:
7968 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007969 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007970 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007971 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007972 break;
7973 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007974 case Instruction::Trunc:
7975 case Instruction::ZExt:
7976 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007977 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007978 // just return the source. There's no need to insert it because it is not
7979 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007980 if (I->getOperand(0)->getType() == Ty)
7981 return I->getOperand(0);
7982
Chris Lattner8114b712008-06-18 04:00:49 +00007983 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007984 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007985 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007986 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007987 case Instruction::Select: {
7988 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7989 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7990 Res = SelectInst::Create(I->getOperand(0), True, False);
7991 break;
7992 }
Chris Lattner8114b712008-06-18 04:00:49 +00007993 case Instruction::PHI: {
7994 PHINode *OPN = cast<PHINode>(I);
7995 PHINode *NPN = PHINode::Create(Ty);
7996 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7997 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7998 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7999 }
8000 Res = NPN;
8001 break;
8002 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008003 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008004 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008005 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008006 break;
8007 }
8008
Chris Lattner8114b712008-06-18 04:00:49 +00008009 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008010 return InsertNewInstBefore(Res, *I);
8011}
8012
Reid Spencer3da59db2006-11-27 01:05:10 +00008013/// @brief Implement the transforms common to all CastInst visitors.
8014Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008015 Value *Src = CI.getOperand(0);
8016
Dan Gohman23d9d272007-05-11 21:10:54 +00008017 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008018 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008019 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008020 if (Instruction::CastOps opc =
8021 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8022 // The first cast (CSrc) is eliminable so we need to fix up or replace
8023 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008024 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008025 }
8026 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008027
Reid Spencer3da59db2006-11-27 01:05:10 +00008028 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008029 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8030 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8031 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008032
8033 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008034 if (isa<PHINode>(Src))
8035 if (Instruction *NV = FoldOpIntoPhi(CI))
8036 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008037
Reid Spencer3da59db2006-11-27 01:05:10 +00008038 return 0;
8039}
8040
Chris Lattner46cd5a12009-01-09 05:44:56 +00008041/// FindElementAtOffset - Given a type and a constant offset, determine whether
8042/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008043/// the specified offset. If so, fill them into NewIndices and return the
8044/// resultant element type, otherwise return null.
8045static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8046 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008047 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008048 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008049 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008050 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008051
8052 // Start with the index over the outer type. Note that the type size
8053 // might be zero (even if the offset isn't zero) if the indexed type
8054 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008055 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008056 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008057 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008058 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008059 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008060
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008061 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008062 if (Offset < 0) {
8063 --FirstIdx;
8064 Offset += TySize;
8065 assert(Offset >= 0);
8066 }
8067 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8068 }
8069
Owen Andersoneed707b2009-07-24 23:12:02 +00008070 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008071
8072 // Index into the types. If we fail, set OrigBase to null.
8073 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008074 // Indexing into tail padding between struct/array elements.
8075 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008076 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008077
Chris Lattner46cd5a12009-01-09 05:44:56 +00008078 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8079 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008080 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8081 "Offset must stay within the indexed type");
8082
Chris Lattner46cd5a12009-01-09 05:44:56 +00008083 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008084 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008085
8086 Offset -= SL->getElementOffset(Elt);
8087 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008088 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008089 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008090 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008091 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008092 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008093 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008094 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008095 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008096 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008097 }
8098 }
8099
Chris Lattner3914f722009-01-24 01:00:13 +00008100 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008101}
8102
Chris Lattnerd3e28342007-04-27 17:44:50 +00008103/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8104Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8105 Value *Src = CI.getOperand(0);
8106
Chris Lattnerd3e28342007-04-27 17:44:50 +00008107 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008108 // If casting the result of a getelementptr instruction with no offset, turn
8109 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008110 if (GEP->hasAllZeroIndices()) {
8111 // Changing the cast operand is usually not a good idea but it is safe
8112 // here because the pointer operand is being replaced with another
8113 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008114 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008115 CI.setOperand(0, GEP->getOperand(0));
8116 return &CI;
8117 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008118
8119 // If the GEP has a single use, and the base pointer is a bitcast, and the
8120 // GEP computes a constant offset, see if we can convert these three
8121 // instructions into fewer. This typically happens with unions and other
8122 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008123 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008124 if (GEP->hasAllConstantIndices()) {
8125 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008126 ConstantInt *OffsetV =
8127 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008128 int64_t Offset = OffsetV->getSExtValue();
8129
8130 // Get the base pointer input of the bitcast, and the type it points to.
8131 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8132 const Type *GEPIdxTy =
8133 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008134 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008135 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008136 // If we were able to index down into an element, create the GEP
8137 // and bitcast the result. This eliminates one bitcast, potentially
8138 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008139 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8140 Builder->CreateInBoundsGEP(OrigBase,
8141 NewIndices.begin(), NewIndices.end()) :
8142 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008143 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008144
Chris Lattner46cd5a12009-01-09 05:44:56 +00008145 if (isa<BitCastInst>(CI))
8146 return new BitCastInst(NGEP, CI.getType());
8147 assert(isa<PtrToIntInst>(CI));
8148 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008149 }
8150 }
8151 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008152 }
8153
8154 return commonCastTransforms(CI);
8155}
8156
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008157/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8158/// type like i42. We don't want to introduce operations on random non-legal
8159/// integer types where they don't already exist in the code. In the future,
8160/// we should consider making this based off target-data, so that 32-bit targets
8161/// won't get i64 operations etc.
8162static bool isSafeIntegerType(const Type *Ty) {
8163 switch (Ty->getPrimitiveSizeInBits()) {
8164 case 8:
8165 case 16:
8166 case 32:
8167 case 64:
8168 return true;
8169 default:
8170 return false;
8171 }
8172}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008173
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008174/// commonIntCastTransforms - This function implements the common transforms
8175/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008176Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8177 if (Instruction *Result = commonCastTransforms(CI))
8178 return Result;
8179
8180 Value *Src = CI.getOperand(0);
8181 const Type *SrcTy = Src->getType();
8182 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008183 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8184 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008185
Reid Spencer3da59db2006-11-27 01:05:10 +00008186 // See if we can simplify any instructions used by the LHS whose sole
8187 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008188 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008189 return &CI;
8190
8191 // If the source isn't an instruction or has more than one use then we
8192 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008193 Instruction *SrcI = dyn_cast<Instruction>(Src);
8194 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008195 return 0;
8196
Chris Lattnerc739cd62007-03-03 05:27:34 +00008197 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008198 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008199 // Only do this if the dest type is a simple type, don't convert the
8200 // expression tree to something weird like i93 unless the source is also
8201 // strange.
8202 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008203 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8204 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008205 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008206 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008207 // eliminates the cast, so it is always a win. If this is a zero-extension,
8208 // we need to do an AND to maintain the clear top-part of the computation,
8209 // so we require that the input have eliminated at least one cast. If this
8210 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008211 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008212 bool DoXForm = false;
8213 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008214 switch (CI.getOpcode()) {
8215 default:
8216 // All the others use floating point so we shouldn't actually
8217 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008218 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008219 case Instruction::Trunc:
8220 DoXForm = true;
8221 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008222 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008223 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008224 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008225 // If it's unnecessary to issue an AND to clear the high bits, it's
8226 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008227 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008228 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8229 if (MaskedValueIsZero(TryRes, Mask))
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);
8235 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008236 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008237 }
Evan Chengf35fd542009-01-15 17:01:23 +00008238 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008239 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008240 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008241 // If we do not have to emit the truncate + sext pair, then it's always
8242 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008243 //
8244 // It's not safe to eliminate the trunc + sext pair if one of the
8245 // eliminated cast is a truncate. e.g.
8246 // t2 = trunc i32 t1 to i16
8247 // t3 = sext i16 t2 to i32
8248 // !=
8249 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008250 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008251 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8252 if (NumSignBits > (DestBitSize - SrcBitSize))
8253 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008254
8255 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008256 if (TryI->use_empty())
8257 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008258 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008259 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008260 }
Evan Chengf35fd542009-01-15 17:01:23 +00008261 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008262
8263 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008264 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8265 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008266 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8267 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008268 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008269 // Just replace this cast with the result.
8270 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008271
Reid Spencer3da59db2006-11-27 01:05:10 +00008272 assert(Res->getType() == DestTy);
8273 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008274 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008275 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 // Just replace this cast with the result.
8277 return ReplaceInstUsesWith(CI, Res);
8278 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008279 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008280
8281 // If the high bits are already zero, just replace this cast with the
8282 // result.
8283 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8284 if (MaskedValueIsZero(Res, Mask))
8285 return ReplaceInstUsesWith(CI, Res);
8286
8287 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008288 Constant *C = ConstantInt::get(*Context,
8289 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008290 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008291 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008292 case Instruction::SExt: {
8293 // If the high bits are already filled with sign bit, just replace this
8294 // cast with the result.
8295 unsigned NumSignBits = ComputeNumSignBits(Res);
8296 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008297 return ReplaceInstUsesWith(CI, Res);
8298
Reid Spencer3da59db2006-11-27 01:05:10 +00008299 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008300 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008301 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008302 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008303 }
8304 }
8305
8306 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8307 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8308
8309 switch (SrcI->getOpcode()) {
8310 case Instruction::Add:
8311 case Instruction::Mul:
8312 case Instruction::And:
8313 case Instruction::Or:
8314 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008315 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008316 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8317 // Don't insert two casts unless at least one can be eliminated.
8318 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008319 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
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::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008323 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008324 }
8325 }
8326
8327 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8328 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8329 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008330 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008331 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008332 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008333 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008334 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008335 }
8336 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008337
Eli Friedman65445c52009-07-13 21:45:57 +00008338 case Instruction::Shl: {
8339 // Canonicalize trunc inside shl, if we can.
8340 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8341 if (CI && DestBitSize < SrcBitSize &&
8342 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008343 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8344 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008345 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008346 }
8347 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008348 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008349 }
8350 return 0;
8351}
8352
Chris Lattner8a9f5712007-04-11 06:57:46 +00008353Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008354 if (Instruction *Result = commonIntCastTransforms(CI))
8355 return Result;
8356
8357 Value *Src = CI.getOperand(0);
8358 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008359 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8360 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008361
8362 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008363 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008364 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008365 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008366 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008367 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008368 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008369
Chris Lattner4f9797d2009-03-24 18:15:30 +00008370 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8371 ConstantInt *ShAmtV = 0;
8372 Value *ShiftOp = 0;
8373 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008374 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008375 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8376
8377 // Get a mask for the bits shifting in.
8378 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8379 if (MaskedValueIsZero(ShiftOp, Mask)) {
8380 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008381 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008382
8383 // Okay, we can shrink this. Truncate the input, then return a new
8384 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008385 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008386 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008387 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008388 }
8389 }
8390
8391 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008392}
8393
Evan Chengb98a10e2008-03-24 00:21:34 +00008394/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8395/// in order to eliminate the icmp.
8396Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8397 bool DoXform) {
8398 // If we are just checking for a icmp eq of a single bit and zext'ing it
8399 // to an integer, then shift the bit to the appropriate place and then
8400 // cast to integer to avoid the comparison.
8401 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8402 const APInt &Op1CV = Op1C->getValue();
8403
8404 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8405 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8406 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8407 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8408 if (!DoXform) return ICI;
8409
8410 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008411 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008412 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008413 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008414 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008415 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008416
8417 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008418 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008419 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008420 }
8421
8422 return ReplaceInstUsesWith(CI, In);
8423 }
8424
8425
8426
8427 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8428 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8429 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8430 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8431 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8432 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8433 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8434 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8435 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8436 // This only works for EQ and NE
8437 ICI->isEquality()) {
8438 // If Op1C some other power of two, convert:
8439 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8440 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8441 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8442 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8443
8444 APInt KnownZeroMask(~KnownZero);
8445 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8446 if (!DoXform) return ICI;
8447
8448 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8449 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8450 // (X&4) == 2 --> false
8451 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008452 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008453 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008454 return ReplaceInstUsesWith(CI, Res);
8455 }
8456
8457 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8458 Value *In = ICI->getOperand(0);
8459 if (ShiftAmt) {
8460 // Perform a logical shr by shiftamt.
8461 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008462 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8463 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008464 }
8465
8466 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008467 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008468 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008469 }
8470
8471 if (CI.getType() == In->getType())
8472 return ReplaceInstUsesWith(CI, In);
8473 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008474 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008475 }
8476 }
8477 }
8478
8479 return 0;
8480}
8481
Chris Lattner8a9f5712007-04-11 06:57:46 +00008482Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008483 // If one of the common conversion will work ..
8484 if (Instruction *Result = commonIntCastTransforms(CI))
8485 return Result;
8486
8487 Value *Src = CI.getOperand(0);
8488
Chris Lattnera84f47c2009-02-17 20:47:23 +00008489 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8490 // types and if the sizes are just right we can convert this into a logical
8491 // 'and' which will be much cheaper than the pair of casts.
8492 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8493 // Get the sizes of the types involved. We know that the intermediate type
8494 // will be smaller than A or C, but don't know the relation between A and C.
8495 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008496 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8497 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8498 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008499 // If we're actually extending zero bits, then if
8500 // SrcSize < DstSize: zext(a & mask)
8501 // SrcSize == DstSize: a & mask
8502 // SrcSize > DstSize: trunc(a) & mask
8503 if (SrcSize < DstSize) {
8504 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008505 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008506 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008507 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008508 }
8509
8510 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008511 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008512 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008513 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008514 }
8515 if (SrcSize > DstSize) {
8516 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008517 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008518 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008519 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008520 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008521 }
8522 }
8523
Evan Chengb98a10e2008-03-24 00:21:34 +00008524 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8525 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008526
Evan Chengb98a10e2008-03-24 00:21:34 +00008527 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8528 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8529 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8530 // of the (zext icmp) will be transformed.
8531 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8532 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8533 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8534 (transformZExtICmp(LHS, CI, false) ||
8535 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008536 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8537 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008538 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008539 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008540 }
8541
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008542 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008543 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8544 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8545 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8546 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008547 if (TI0->getType() == CI.getType())
8548 return
8549 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008550 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008551 }
8552
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008553 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8554 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8555 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8556 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8557 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8558 And->getOperand(1) == C)
8559 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8560 Value *TI0 = TI->getOperand(0);
8561 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008562 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008563 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008564 return BinaryOperator::CreateXor(NewAnd, ZC);
8565 }
8566 }
8567
Reid Spencer3da59db2006-11-27 01:05:10 +00008568 return 0;
8569}
8570
Chris Lattner8a9f5712007-04-11 06:57:46 +00008571Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008572 if (Instruction *I = commonIntCastTransforms(CI))
8573 return I;
8574
Chris Lattner8a9f5712007-04-11 06:57:46 +00008575 Value *Src = CI.getOperand(0);
8576
Dan Gohman1975d032008-10-30 20:40:10 +00008577 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008578 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008579 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008580 Constant::getAllOnesValue(CI.getType()),
8581 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008582
8583 // See if the value being truncated is already sign extended. If so, just
8584 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008585 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008586 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008587 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8588 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8589 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008590 unsigned NumSignBits = ComputeNumSignBits(Op);
8591
8592 if (OpBits == DestBits) {
8593 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8594 // bits, it is already ready.
8595 if (NumSignBits > DestBits-MidBits)
8596 return ReplaceInstUsesWith(CI, Op);
8597 } else if (OpBits < DestBits) {
8598 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8599 // bits, just sext from i32.
8600 if (NumSignBits > OpBits-MidBits)
8601 return new SExtInst(Op, CI.getType(), "tmp");
8602 } else {
8603 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8604 // bits, just truncate to i32.
8605 if (NumSignBits > OpBits-MidBits)
8606 return new TruncInst(Op, CI.getType(), "tmp");
8607 }
8608 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008609
8610 // If the input is a shl/ashr pair of a same constant, then this is a sign
8611 // extension from a smaller value. If we could trust arbitrary bitwidth
8612 // integers, we could turn this into a truncate to the smaller bit and then
8613 // use a sext for the whole extension. Since we don't, look deeper and check
8614 // for a truncate. If the source and dest are the same type, eliminate the
8615 // trunc and extend and just do shifts. For example, turn:
8616 // %a = trunc i32 %i to i8
8617 // %b = shl i8 %a, 6
8618 // %c = ashr i8 %b, 6
8619 // %d = sext i8 %c to i32
8620 // into:
8621 // %a = shl i32 %i, 30
8622 // %d = ashr i32 %a, 30
8623 Value *A = 0;
8624 ConstantInt *BA = 0, *CA = 0;
8625 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008626 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008627 BA == CA && isa<TruncInst>(A)) {
8628 Value *I = cast<TruncInst>(A)->getOperand(0);
8629 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008630 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8631 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008632 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008633 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008634 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008635 return BinaryOperator::CreateAShr(I, ShAmtV);
8636 }
8637 }
8638
Chris Lattnerba417832007-04-11 06:12:58 +00008639 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008640}
8641
Chris Lattnerb7530652008-01-27 05:29:54 +00008642/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8643/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008644static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008645 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008646 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008647 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008648 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8649 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008650 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008651 return 0;
8652}
8653
8654/// LookThroughFPExtensions - If this is an fp extension instruction, look
8655/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008656static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008657 if (Instruction *I = dyn_cast<Instruction>(V))
8658 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008659 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008660
8661 // If this value is a constant, return the constant in the smallest FP type
8662 // that can accurately represent it. This allows us to turn
8663 // (float)((double)X+2.0) into x+2.0f.
8664 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008665 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008666 return V; // No constant folding of this.
8667 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008668 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008669 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008670 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008671 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008672 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008673 return V;
8674 // Don't try to shrink to various long double types.
8675 }
8676
8677 return V;
8678}
8679
8680Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8681 if (Instruction *I = commonCastTransforms(CI))
8682 return I;
8683
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008684 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008685 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008686 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008687 // many builtins (sqrt, etc).
8688 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8689 if (OpI && OpI->hasOneUse()) {
8690 switch (OpI->getOpcode()) {
8691 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008692 case Instruction::FAdd:
8693 case Instruction::FSub:
8694 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008695 case Instruction::FDiv:
8696 case Instruction::FRem:
8697 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008698 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8699 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008700 if (LHSTrunc->getType() != SrcTy &&
8701 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008702 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008703 // If the source types were both smaller than the destination type of
8704 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008705 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8706 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008707 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8708 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008709 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008710 }
8711 }
8712 break;
8713 }
8714 }
8715 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008716}
8717
8718Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8719 return commonCastTransforms(CI);
8720}
8721
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008722Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008723 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8724 if (OpI == 0)
8725 return commonCastTransforms(FI);
8726
8727 // fptoui(uitofp(X)) --> X
8728 // fptoui(sitofp(X)) --> X
8729 // This is safe if the intermediate type has enough bits in its mantissa to
8730 // accurately represent all values of X. For example, do not do this with
8731 // i64->float->i64. This is also safe for sitofp case, because any negative
8732 // 'X' value would cause an undefined result for the fptoui.
8733 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8734 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008735 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008736 OpI->getType()->getFPMantissaWidth())
8737 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008738
8739 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008740}
8741
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008742Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008743 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8744 if (OpI == 0)
8745 return commonCastTransforms(FI);
8746
8747 // fptosi(sitofp(X)) --> X
8748 // fptosi(uitofp(X)) --> X
8749 // This is safe if the intermediate type has enough bits in its mantissa to
8750 // accurately represent all values of X. For example, do not do this with
8751 // i64->float->i64. This is also safe for sitofp case, because any negative
8752 // 'X' value would cause an undefined result for the fptoui.
8753 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8754 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008755 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008756 OpI->getType()->getFPMantissaWidth())
8757 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008758
8759 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008760}
8761
8762Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8763 return commonCastTransforms(CI);
8764}
8765
8766Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8767 return commonCastTransforms(CI);
8768}
8769
Chris Lattnera0e69692009-03-24 18:35:40 +00008770Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8771 // If the destination integer type is smaller than the intptr_t type for
8772 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8773 // trunc to be exposed to other transforms. Don't do this for extending
8774 // ptrtoint's, because we don't know if the target sign or zero extends its
8775 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008776 if (TD &&
8777 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008778 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8779 TD->getIntPtrType(CI.getContext()),
8780 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008781 return new TruncInst(P, CI.getType());
8782 }
8783
Chris Lattnerd3e28342007-04-27 17:44:50 +00008784 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008785}
8786
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008787Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008788 // If the source integer type is larger than the intptr_t type for
8789 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8790 // allows the trunc to be exposed to other transforms. Don't do this for
8791 // extending inttoptr's, because we don't know if the target sign or zero
8792 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008793 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008794 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008795 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8796 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008797 return new IntToPtrInst(P, CI.getType());
8798 }
8799
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008800 if (Instruction *I = commonCastTransforms(CI))
8801 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008802
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008803 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008804}
8805
Chris Lattnerd3e28342007-04-27 17:44:50 +00008806Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008807 // If the operands are integer typed then apply the integer transforms,
8808 // otherwise just apply the common ones.
8809 Value *Src = CI.getOperand(0);
8810 const Type *SrcTy = Src->getType();
8811 const Type *DestTy = CI.getType();
8812
Eli Friedman7e25d452009-07-13 20:53:00 +00008813 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008814 if (Instruction *I = commonPointerCastTransforms(CI))
8815 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008816 } else {
8817 if (Instruction *Result = commonCastTransforms(CI))
8818 return Result;
8819 }
8820
8821
8822 // Get rid of casts from one type to the same type. These are useless and can
8823 // be replaced by the operand.
8824 if (DestTy == Src->getType())
8825 return ReplaceInstUsesWith(CI, Src);
8826
Reid Spencer3da59db2006-11-27 01:05:10 +00008827 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008828 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8829 const Type *DstElTy = DstPTy->getElementType();
8830 const Type *SrcElTy = SrcPTy->getElementType();
8831
Nate Begeman83ad90a2008-03-31 00:22:16 +00008832 // If the address spaces don't match, don't eliminate the bitcast, which is
8833 // required for changing types.
8834 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8835 return 0;
8836
Victor Hernandez83d63912009-09-18 22:35:49 +00008837 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008838 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008839 // There is no need to modify malloc calls because it is their bitcast that
8840 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008841 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8842 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8843 return V;
8844
Chris Lattnerd717c182007-05-05 22:32:24 +00008845 // If the source and destination are pointers, and this cast is equivalent
8846 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008847 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008848 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008849 unsigned NumZeros = 0;
8850 while (SrcElTy != DstElTy &&
8851 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8852 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8853 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8854 ++NumZeros;
8855 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008856
Chris Lattnerd3e28342007-04-27 17:44:50 +00008857 // If we found a path from the src to dest, create the getelementptr now.
8858 if (SrcElTy == DstElTy) {
8859 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008860 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8861 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008862 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008863 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008864
Eli Friedman2451a642009-07-18 23:06:53 +00008865 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8866 if (DestVTy->getNumElements() == 1) {
8867 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008868 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008869 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008870 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008871 }
8872 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8873 }
8874 }
8875
8876 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8877 if (SrcVTy->getNumElements() == 1) {
8878 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008879 Value *Elem =
8880 Builder->CreateExtractElement(Src,
8881 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008882 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8883 }
8884 }
8885 }
8886
Reid Spencer3da59db2006-11-27 01:05:10 +00008887 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8888 if (SVI->hasOneUse()) {
8889 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8890 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008891 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008892 cast<VectorType>(DestTy)->getNumElements() ==
8893 SVI->getType()->getNumElements() &&
8894 SVI->getType()->getNumElements() ==
8895 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008896 CastInst *Tmp;
8897 // If either of the operands is a cast from CI.getType(), then
8898 // evaluating the shuffle in the casted destination's type will allow
8899 // us to eliminate at least one cast.
8900 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8901 Tmp->getOperand(0)->getType() == DestTy) ||
8902 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8903 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008904 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8905 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008906 // Return a new shuffle vector. Use the same element ID's, as we
8907 // know the vector types match #elts.
8908 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008909 }
8910 }
8911 }
8912 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008913 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008914}
8915
Chris Lattnere576b912004-04-09 23:46:01 +00008916/// GetSelectFoldableOperands - We want to turn code that looks like this:
8917/// %C = or %A, %B
8918/// %D = select %cond, %C, %A
8919/// into:
8920/// %C = select %cond, %B, 0
8921/// %D = or %A, %C
8922///
8923/// Assuming that the specified instruction is an operand to the select, return
8924/// a bitmask indicating which operands of this instruction are foldable if they
8925/// equal the other incoming value of the select.
8926///
8927static unsigned GetSelectFoldableOperands(Instruction *I) {
8928 switch (I->getOpcode()) {
8929 case Instruction::Add:
8930 case Instruction::Mul:
8931 case Instruction::And:
8932 case Instruction::Or:
8933 case Instruction::Xor:
8934 return 3; // Can fold through either operand.
8935 case Instruction::Sub: // Can only fold on the amount subtracted.
8936 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008937 case Instruction::LShr:
8938 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008939 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008940 default:
8941 return 0; // Cannot fold
8942 }
8943}
8944
8945/// GetSelectFoldableConstant - For the same transformation as the previous
8946/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008947static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008948 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008949 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008950 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008951 case Instruction::Add:
8952 case Instruction::Sub:
8953 case Instruction::Or:
8954 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008955 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008956 case Instruction::LShr:
8957 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008958 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008959 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008960 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008961 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008962 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008963 }
8964}
8965
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008966/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8967/// have the same opcode and only one use each. Try to simplify this.
8968Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8969 Instruction *FI) {
8970 if (TI->getNumOperands() == 1) {
8971 // If this is a non-volatile load or a cast from the same type,
8972 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008973 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008974 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8975 return 0;
8976 } else {
8977 return 0; // unknown unary op.
8978 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008979
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008980 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008981 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008982 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008983 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008984 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008985 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008986 }
8987
Reid Spencer832254e2007-02-02 02:16:23 +00008988 // Only handle binary operators here.
8989 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008990 return 0;
8991
8992 // Figure out if the operations have any operands in common.
8993 Value *MatchOp, *OtherOpT, *OtherOpF;
8994 bool MatchIsOpZero;
8995 if (TI->getOperand(0) == FI->getOperand(0)) {
8996 MatchOp = TI->getOperand(0);
8997 OtherOpT = TI->getOperand(1);
8998 OtherOpF = FI->getOperand(1);
8999 MatchIsOpZero = true;
9000 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9001 MatchOp = TI->getOperand(1);
9002 OtherOpT = TI->getOperand(0);
9003 OtherOpF = FI->getOperand(0);
9004 MatchIsOpZero = false;
9005 } else if (!TI->isCommutative()) {
9006 return 0;
9007 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9008 MatchOp = TI->getOperand(0);
9009 OtherOpT = TI->getOperand(1);
9010 OtherOpF = FI->getOperand(0);
9011 MatchIsOpZero = true;
9012 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9013 MatchOp = TI->getOperand(1);
9014 OtherOpT = TI->getOperand(0);
9015 OtherOpF = FI->getOperand(1);
9016 MatchIsOpZero = true;
9017 } else {
9018 return 0;
9019 }
9020
9021 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009022 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9023 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009024 InsertNewInstBefore(NewSI, SI);
9025
9026 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9027 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009028 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009029 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009030 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009031 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009032 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009033 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009034}
9035
Evan Chengde621922009-03-31 20:42:45 +00009036static bool isSelect01(Constant *C1, Constant *C2) {
9037 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9038 if (!C1I)
9039 return false;
9040 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9041 if (!C2I)
9042 return false;
9043 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9044}
9045
9046/// FoldSelectIntoOp - Try fold the select into one of the operands to
9047/// facilitate further optimization.
9048Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9049 Value *FalseVal) {
9050 // See the comment above GetSelectFoldableOperands for a description of the
9051 // transformation we are doing here.
9052 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9053 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9054 !isa<Constant>(FalseVal)) {
9055 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9056 unsigned OpToFold = 0;
9057 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9058 OpToFold = 1;
9059 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9060 OpToFold = 2;
9061 }
9062
9063 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009064 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009065 Value *OOp = TVI->getOperand(2-OpToFold);
9066 // Avoid creating select between 2 constants unless it's selecting
9067 // between 0 and 1.
9068 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9069 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9070 InsertNewInstBefore(NewSel, SI);
9071 NewSel->takeName(TVI);
9072 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9073 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009074 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009075 }
9076 }
9077 }
9078 }
9079 }
9080
9081 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9082 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9083 !isa<Constant>(TrueVal)) {
9084 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9085 unsigned OpToFold = 0;
9086 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9087 OpToFold = 1;
9088 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9089 OpToFold = 2;
9090 }
9091
9092 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009093 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009094 Value *OOp = FVI->getOperand(2-OpToFold);
9095 // Avoid creating select between 2 constants unless it's selecting
9096 // between 0 and 1.
9097 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9098 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9099 InsertNewInstBefore(NewSel, SI);
9100 NewSel->takeName(FVI);
9101 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9102 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009103 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009104 }
9105 }
9106 }
9107 }
9108 }
9109
9110 return 0;
9111}
9112
Dan Gohman81b28ce2008-09-16 18:46:06 +00009113/// visitSelectInstWithICmp - Visit a SelectInst that has an
9114/// ICmpInst as its first operand.
9115///
9116Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9117 ICmpInst *ICI) {
9118 bool Changed = false;
9119 ICmpInst::Predicate Pred = ICI->getPredicate();
9120 Value *CmpLHS = ICI->getOperand(0);
9121 Value *CmpRHS = ICI->getOperand(1);
9122 Value *TrueVal = SI.getTrueValue();
9123 Value *FalseVal = SI.getFalseValue();
9124
9125 // Check cases where the comparison is with a constant that
9126 // can be adjusted to fit the min/max idiom. We may edit ICI in
9127 // place here, so make sure the select is the only user.
9128 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009129 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009130 switch (Pred) {
9131 default: break;
9132 case ICmpInst::ICMP_ULT:
9133 case ICmpInst::ICMP_SLT: {
9134 // X < MIN ? T : F --> F
9135 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9136 return ReplaceInstUsesWith(SI, FalseVal);
9137 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009138 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009139 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9140 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9141 Pred = ICmpInst::getSwappedPredicate(Pred);
9142 CmpRHS = AdjustedRHS;
9143 std::swap(FalseVal, TrueVal);
9144 ICI->setPredicate(Pred);
9145 ICI->setOperand(1, CmpRHS);
9146 SI.setOperand(1, TrueVal);
9147 SI.setOperand(2, FalseVal);
9148 Changed = true;
9149 }
9150 break;
9151 }
9152 case ICmpInst::ICMP_UGT:
9153 case ICmpInst::ICMP_SGT: {
9154 // X > MAX ? T : F --> F
9155 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9156 return ReplaceInstUsesWith(SI, FalseVal);
9157 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009158 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009159 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9160 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9161 Pred = ICmpInst::getSwappedPredicate(Pred);
9162 CmpRHS = AdjustedRHS;
9163 std::swap(FalseVal, TrueVal);
9164 ICI->setPredicate(Pred);
9165 ICI->setOperand(1, CmpRHS);
9166 SI.setOperand(1, TrueVal);
9167 SI.setOperand(2, FalseVal);
9168 Changed = true;
9169 }
9170 break;
9171 }
9172 }
9173
Dan Gohman1975d032008-10-30 20:40:10 +00009174 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9175 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009176 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009177 if (match(TrueVal, m_ConstantInt<-1>()) &&
9178 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009179 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009180 else if (match(TrueVal, m_ConstantInt<0>()) &&
9181 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009182 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9183
Dan Gohman1975d032008-10-30 20:40:10 +00009184 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9185 // If we are just checking for a icmp eq of a single bit and zext'ing it
9186 // to an integer, then shift the bit to the appropriate place and then
9187 // cast to integer to avoid the comparison.
9188 const APInt &Op1CV = CI->getValue();
9189
9190 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9191 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9192 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009193 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009194 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009195 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009196 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009197 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009198 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009199 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009200 if (In->getType() != SI.getType())
9201 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009202 true/*SExt*/, "tmp", ICI);
9203
9204 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009205 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009206 In->getName()+".not"), *ICI);
9207
9208 return ReplaceInstUsesWith(SI, In);
9209 }
9210 }
9211 }
9212
Dan Gohman81b28ce2008-09-16 18:46:06 +00009213 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9214 // Transform (X == Y) ? X : Y -> Y
9215 if (Pred == ICmpInst::ICMP_EQ)
9216 return ReplaceInstUsesWith(SI, FalseVal);
9217 // Transform (X != Y) ? X : Y -> X
9218 if (Pred == ICmpInst::ICMP_NE)
9219 return ReplaceInstUsesWith(SI, TrueVal);
9220 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9221
9222 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9223 // Transform (X == Y) ? Y : X -> X
9224 if (Pred == ICmpInst::ICMP_EQ)
9225 return ReplaceInstUsesWith(SI, FalseVal);
9226 // Transform (X != Y) ? Y : X -> Y
9227 if (Pred == ICmpInst::ICMP_NE)
9228 return ReplaceInstUsesWith(SI, TrueVal);
9229 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9230 }
9231
9232 /// NOTE: if we wanted to, this is where to detect integer ABS
9233
9234 return Changed ? &SI : 0;
9235}
9236
Chris Lattner3d69f462004-03-12 05:52:32 +00009237Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009238 Value *CondVal = SI.getCondition();
9239 Value *TrueVal = SI.getTrueValue();
9240 Value *FalseVal = SI.getFalseValue();
9241
9242 // select true, X, Y -> X
9243 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009244 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009245 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009246
9247 // select C, X, X -> X
9248 if (TrueVal == FalseVal)
9249 return ReplaceInstUsesWith(SI, TrueVal);
9250
Chris Lattnere87597f2004-10-16 18:11:37 +00009251 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9252 return ReplaceInstUsesWith(SI, FalseVal);
9253 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9254 return ReplaceInstUsesWith(SI, TrueVal);
9255 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9256 if (isa<Constant>(TrueVal))
9257 return ReplaceInstUsesWith(SI, TrueVal);
9258 else
9259 return ReplaceInstUsesWith(SI, FalseVal);
9260 }
9261
Owen Anderson1d0be152009-08-13 21:58:54 +00009262 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009263 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009264 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009265 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009266 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009267 } else {
9268 // Change: A = select B, false, C --> A = and !B, C
9269 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009270 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009271 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009272 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009273 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009274 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009275 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009276 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009277 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009278 } else {
9279 // Change: A = select B, C, true --> A = or !B, C
9280 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009281 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009282 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009283 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009284 }
9285 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009286
9287 // select a, b, a -> a&b
9288 // select a, a, b -> a|b
9289 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009290 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009291 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009292 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009293 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009294
Chris Lattner2eefe512004-04-09 19:05:30 +00009295 // Selecting between two integer constants?
9296 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9297 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009298 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009299 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009300 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009301 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009302 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009303 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009304 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009305 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009306 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009307 }
Chris Lattner457dd822004-06-09 07:59:58 +00009308
Reid Spencere4d87aa2006-12-23 06:05:41 +00009309 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009310 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009311 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009312 // non-constant value, eliminate this whole mess. This corresponds to
9313 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009314 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009315 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009316 cast<Constant>(IC->getOperand(1))->isNullValue())
9317 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9318 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009319 isa<ConstantInt>(ICA->getOperand(1)) &&
9320 (ICA->getOperand(1) == TrueValC ||
9321 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009322 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9323 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009324 // know whether we have a icmp_ne or icmp_eq and whether the
9325 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009326 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009327 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009328 Value *V = ICA;
9329 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009330 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009331 Instruction::Xor, V, ICA->getOperand(1)), SI);
9332 return ReplaceInstUsesWith(SI, V);
9333 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009334 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009335 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009336
9337 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009338 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9339 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009340 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009341 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9342 // This is not safe in general for floating point:
9343 // consider X== -0, Y== +0.
9344 // It becomes safe if either operand is a nonzero constant.
9345 ConstantFP *CFPt, *CFPf;
9346 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9347 !CFPt->getValueAPF().isZero()) ||
9348 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9349 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009350 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009351 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009352 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009353 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009354 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009355 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009356
Reid Spencere4d87aa2006-12-23 06:05:41 +00009357 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009358 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009359 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9360 // This is not safe in general for floating point:
9361 // consider X== -0, Y== +0.
9362 // It becomes safe if either operand is a nonzero constant.
9363 ConstantFP *CFPt, *CFPf;
9364 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9365 !CFPt->getValueAPF().isZero()) ||
9366 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9367 !CFPf->getValueAPF().isZero()))
9368 return ReplaceInstUsesWith(SI, FalseVal);
9369 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009370 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009371 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9372 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009373 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009374 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009375 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009376 }
9377
9378 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009379 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9380 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9381 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009382
Chris Lattner87875da2005-01-13 22:52:24 +00009383 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9384 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9385 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009386 Instruction *AddOp = 0, *SubOp = 0;
9387
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009388 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9389 if (TI->getOpcode() == FI->getOpcode())
9390 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9391 return IV;
9392
9393 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9394 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009395 if ((TI->getOpcode() == Instruction::Sub &&
9396 FI->getOpcode() == Instruction::Add) ||
9397 (TI->getOpcode() == Instruction::FSub &&
9398 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009399 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009400 } else if ((FI->getOpcode() == Instruction::Sub &&
9401 TI->getOpcode() == Instruction::Add) ||
9402 (FI->getOpcode() == Instruction::FSub &&
9403 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009404 AddOp = TI; SubOp = FI;
9405 }
9406
9407 if (AddOp) {
9408 Value *OtherAddOp = 0;
9409 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9410 OtherAddOp = AddOp->getOperand(1);
9411 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9412 OtherAddOp = AddOp->getOperand(0);
9413 }
9414
9415 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009416 // So at this point we know we have (Y -> OtherAddOp):
9417 // select C, (add X, Y), (sub X, Z)
9418 Value *NegVal; // Compute -Z
9419 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009420 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009421 } else {
9422 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009423 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009424 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009425 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009426
9427 Value *NewTrueOp = OtherAddOp;
9428 Value *NewFalseOp = NegVal;
9429 if (AddOp != TI)
9430 std::swap(NewTrueOp, NewFalseOp);
9431 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009432 SelectInst::Create(CondVal, NewTrueOp,
9433 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009434
9435 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009436 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009437 }
9438 }
9439 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009440
Chris Lattnere576b912004-04-09 23:46:01 +00009441 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009442 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009443 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9444 if (FoldI)
9445 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009446 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009447
Chris Lattner5d1704d2009-09-27 19:57:57 +00009448 // See if we can fold the select into a phi node. The true/false values have
9449 // to be live in the predecessor blocks.
9450 if (isa<PHINode>(SI.getCondition()) &&
9451 isa<Constant>(SI.getTrueValue()) &&
9452 isa<Constant>(SI.getFalseValue()))
9453 if (Instruction *NV = FoldOpIntoPhi(SI))
9454 return NV;
9455
Chris Lattnera1df33c2005-04-24 07:30:14 +00009456 if (BinaryOperator::isNot(CondVal)) {
9457 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9458 SI.setOperand(1, FalseVal);
9459 SI.setOperand(2, TrueVal);
9460 return &SI;
9461 }
9462
Chris Lattner3d69f462004-03-12 05:52:32 +00009463 return 0;
9464}
9465
Dan Gohmaneee962e2008-04-10 18:43:06 +00009466/// EnforceKnownAlignment - If the specified pointer points to an object that
9467/// we control, modify the object's alignment to PrefAlign. This isn't
9468/// often possible though. If alignment is important, a more reliable approach
9469/// is to simply align all global variables and allocation instructions to
9470/// their preferred alignment from the beginning.
9471///
9472static unsigned EnforceKnownAlignment(Value *V,
9473 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009474
Dan Gohmaneee962e2008-04-10 18:43:06 +00009475 User *U = dyn_cast<User>(V);
9476 if (!U) return Align;
9477
Dan Gohmanca178902009-07-17 20:47:02 +00009478 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009479 default: break;
9480 case Instruction::BitCast:
9481 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9482 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009483 // If all indexes are zero, it is just the alignment of the base pointer.
9484 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009485 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009486 if (!isa<Constant>(*i) ||
9487 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009488 AllZeroOperands = false;
9489 break;
9490 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009491
9492 if (AllZeroOperands) {
9493 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009494 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009495 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009496 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009497 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009498 }
9499
9500 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9501 // If there is a large requested alignment and we can, bump up the alignment
9502 // of the global.
9503 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009504 if (GV->getAlignment() >= PrefAlign)
9505 Align = GV->getAlignment();
9506 else {
9507 GV->setAlignment(PrefAlign);
9508 Align = PrefAlign;
9509 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009510 }
9511 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9512 // If there is a requested alignment and if this is an alloca, round up. We
9513 // don't do this for malloc, because some systems can't respect the request.
9514 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009515 if (AI->getAlignment() >= PrefAlign)
9516 Align = AI->getAlignment();
9517 else {
9518 AI->setAlignment(PrefAlign);
9519 Align = PrefAlign;
9520 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009521 }
Victor Hernandez83d63912009-09-18 22:35:49 +00009522 // No alignment changes are possible for malloc calls
Dan Gohmaneee962e2008-04-10 18:43:06 +00009523 }
9524
9525 return Align;
9526}
9527
9528/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9529/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9530/// and it is more than the alignment of the ultimate object, see if we can
9531/// increase the alignment of the ultimate object, making this check succeed.
9532unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9533 unsigned PrefAlign) {
9534 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9535 sizeof(PrefAlign) * CHAR_BIT;
9536 APInt Mask = APInt::getAllOnesValue(BitWidth);
9537 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9538 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9539 unsigned TrailZ = KnownZero.countTrailingOnes();
9540 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9541
9542 if (PrefAlign > Align)
9543 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9544
9545 // We don't need to make any adjustment.
9546 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009547}
9548
Chris Lattnerf497b022008-01-13 23:50:23 +00009549Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009550 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009551 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009552 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009553 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009554
9555 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009556 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009557 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009558 return MI;
9559 }
9560
9561 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9562 // load/store.
9563 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9564 if (MemOpLength == 0) return 0;
9565
Chris Lattner37ac6082008-01-14 00:28:35 +00009566 // Source and destination pointer types are always "i8*" for intrinsic. See
9567 // if the size is something we can handle with a single primitive load/store.
9568 // A single load+store correctly handles overlapping memory in the memmove
9569 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009570 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009571 if (Size == 0) return MI; // Delete this mem transfer.
9572
9573 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009574 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009575
Chris Lattner37ac6082008-01-14 00:28:35 +00009576 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009577 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009578 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009579
9580 // Memcpy forces the use of i8* for the source and destination. That means
9581 // that if you're using memcpy to move one double around, you'll get a cast
9582 // from double* to i8*. We'd much rather use a double load+store rather than
9583 // an i64 load+store, here because this improves the odds that the source or
9584 // dest address will be promotable. See if we can find a better type than the
9585 // integer datatype.
9586 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9587 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009588 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009589 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9590 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009591 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009592 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9593 if (STy->getNumElements() == 1)
9594 SrcETy = STy->getElementType(0);
9595 else
9596 break;
9597 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9598 if (ATy->getNumElements() == 1)
9599 SrcETy = ATy->getElementType();
9600 else
9601 break;
9602 } else
9603 break;
9604 }
9605
Dan Gohman8f8e2692008-05-23 01:52:21 +00009606 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009607 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009608 }
9609 }
9610
9611
Chris Lattnerf497b022008-01-13 23:50:23 +00009612 // If the memcpy/memmove provides better alignment info than we can
9613 // infer, use it.
9614 SrcAlign = std::max(SrcAlign, CopyAlign);
9615 DstAlign = std::max(DstAlign, CopyAlign);
9616
Chris Lattner08142f22009-08-30 19:47:22 +00009617 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9618 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009619 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9620 InsertNewInstBefore(L, *MI);
9621 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9622
9623 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009624 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009625 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009626}
Chris Lattner3d69f462004-03-12 05:52:32 +00009627
Chris Lattner69ea9d22008-04-30 06:39:11 +00009628Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9629 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009630 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009631 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009632 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009633 return MI;
9634 }
9635
9636 // Extract the length and alignment and fill if they are constant.
9637 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9638 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009639 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009640 return 0;
9641 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009642 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009643
9644 // If the length is zero, this is a no-op
9645 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9646
9647 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9648 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009649 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009650
9651 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009652 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009653
9654 // Alignment 0 is identity for alignment 1 for memset, but not store.
9655 if (Alignment == 0) Alignment = 1;
9656
9657 // Extract the fill value and store.
9658 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009659 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009660 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009661
9662 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009663 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009664 return MI;
9665 }
9666
9667 return 0;
9668}
9669
9670
Chris Lattner8b0ea312006-01-13 20:11:04 +00009671/// visitCallInst - CallInst simplification. This mostly only handles folding
9672/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9673/// the heavy lifting.
9674///
Chris Lattner9fe38862003-06-19 17:00:31 +00009675Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009676 // If the caller function is nounwind, mark the call as nounwind, even if the
9677 // callee isn't.
9678 if (CI.getParent()->getParent()->doesNotThrow() &&
9679 !CI.doesNotThrow()) {
9680 CI.setDoesNotThrow();
9681 return &CI;
9682 }
9683
Chris Lattner8b0ea312006-01-13 20:11:04 +00009684 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9685 if (!II) return visitCallSite(&CI);
9686
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009687 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9688 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009689 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009690 bool Changed = false;
9691
9692 // memmove/cpy/set of zero bytes is a noop.
9693 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9694 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9695
Chris Lattner35b9e482004-10-12 04:52:52 +00009696 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009697 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009698 // Replace the instruction with just byte operations. We would
9699 // transform other cases to loads/stores, but we don't know if
9700 // alignment is sufficient.
9701 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009702 }
9703
Chris Lattner35b9e482004-10-12 04:52:52 +00009704 // If we have a memmove and the source operation is a constant global,
9705 // then the source and dest pointers can't alias, so we can change this
9706 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009707 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009708 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9709 if (GVSrc->isConstant()) {
9710 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009711 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9712 const Type *Tys[1];
9713 Tys[0] = CI.getOperand(3)->getType();
9714 CI.setOperand(0,
9715 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009716 Changed = true;
9717 }
Chris Lattnera935db82008-05-28 05:30:41 +00009718
9719 // memmove(x,x,size) -> noop.
9720 if (MMI->getSource() == MMI->getDest())
9721 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009722 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009723
Chris Lattner95a959d2006-03-06 20:18:44 +00009724 // If we can determine a pointer alignment that is bigger than currently
9725 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009726 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009727 if (Instruction *I = SimplifyMemTransfer(MI))
9728 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009729 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9730 if (Instruction *I = SimplifyMemSet(MSI))
9731 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009732 }
9733
Chris Lattner8b0ea312006-01-13 20:11:04 +00009734 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009735 }
9736
9737 switch (II->getIntrinsicID()) {
9738 default: break;
9739 case Intrinsic::bswap:
9740 // bswap(bswap(x)) -> x
9741 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9742 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9743 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9744 break;
9745 case Intrinsic::ppc_altivec_lvx:
9746 case Intrinsic::ppc_altivec_lvxl:
9747 case Intrinsic::x86_sse_loadu_ps:
9748 case Intrinsic::x86_sse2_loadu_pd:
9749 case Intrinsic::x86_sse2_loadu_dq:
9750 // Turn PPC lvx -> load if the pointer is known aligned.
9751 // Turn X86 loadups -> load if the pointer is known aligned.
9752 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009753 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9754 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009755 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009756 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009757 break;
9758 case Intrinsic::ppc_altivec_stvx:
9759 case Intrinsic::ppc_altivec_stvxl:
9760 // Turn stvx -> store if the pointer is known aligned.
9761 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9762 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009763 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009764 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009765 return new StoreInst(II->getOperand(1), Ptr);
9766 }
9767 break;
9768 case Intrinsic::x86_sse_storeu_ps:
9769 case Intrinsic::x86_sse2_storeu_pd:
9770 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009771 // Turn X86 storeu -> store if the pointer is known aligned.
9772 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9773 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009774 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009775 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009776 return new StoreInst(II->getOperand(2), Ptr);
9777 }
9778 break;
9779
9780 case Intrinsic::x86_sse_cvttss2si: {
9781 // These intrinsics only demands the 0th element of its input vector. If
9782 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009783 unsigned VWidth =
9784 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9785 APInt DemandedElts(VWidth, 1);
9786 APInt UndefElts(VWidth, 0);
9787 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009788 UndefElts)) {
9789 II->setOperand(1, V);
9790 return II;
9791 }
9792 break;
9793 }
9794
9795 case Intrinsic::ppc_altivec_vperm:
9796 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9797 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9798 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009799
Chris Lattner0521e3c2008-06-18 04:33:20 +00009800 // Check that all of the elements are integer constants or undefs.
9801 bool AllEltsOk = true;
9802 for (unsigned i = 0; i != 16; ++i) {
9803 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9804 !isa<UndefValue>(Mask->getOperand(i))) {
9805 AllEltsOk = false;
9806 break;
9807 }
9808 }
9809
9810 if (AllEltsOk) {
9811 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009812 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9813 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009814 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009815
Chris Lattner0521e3c2008-06-18 04:33:20 +00009816 // Only extract each element once.
9817 Value *ExtractedElts[32];
9818 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9819
Chris Lattnere2ed0572006-04-06 19:19:17 +00009820 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009821 if (isa<UndefValue>(Mask->getOperand(i)))
9822 continue;
9823 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9824 Idx &= 31; // Match the hardware behavior.
9825
9826 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009827 ExtractedElts[Idx] =
9828 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9829 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9830 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009831 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009832
Chris Lattner0521e3c2008-06-18 04:33:20 +00009833 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009834 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9835 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9836 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009837 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009838 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009839 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009840 }
9841 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009842
Chris Lattner0521e3c2008-06-18 04:33:20 +00009843 case Intrinsic::stackrestore: {
9844 // If the save is right next to the restore, remove the restore. This can
9845 // happen when variable allocas are DCE'd.
9846 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9847 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9848 BasicBlock::iterator BI = SS;
9849 if (&*++BI == II)
9850 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009851 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009852 }
9853
9854 // Scan down this block to see if there is another stack restore in the
9855 // same block without an intervening call/alloca.
9856 BasicBlock::iterator BI = II;
9857 TerminatorInst *TI = II->getParent()->getTerminator();
9858 bool CannotRemove = false;
9859 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009860 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009861 CannotRemove = true;
9862 break;
9863 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009864 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9865 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9866 // If there is a stackrestore below this one, remove this one.
9867 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9868 return EraseInstFromFunction(CI);
9869 // Otherwise, ignore the intrinsic.
9870 } else {
9871 // If we found a non-intrinsic call, we can't remove the stack
9872 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009873 CannotRemove = true;
9874 break;
9875 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009876 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009877 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009878
9879 // If the stack restore is in a return/unwind block and if there are no
9880 // allocas or calls between the restore and the return, nuke the restore.
9881 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9882 return EraseInstFromFunction(CI);
9883 break;
9884 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009885 }
9886
Chris Lattner8b0ea312006-01-13 20:11:04 +00009887 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009888}
9889
9890// InvokeInst simplification
9891//
9892Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009893 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009894}
9895
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009896/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9897/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009898static bool isSafeToEliminateVarargsCast(const CallSite CS,
9899 const CastInst * const CI,
9900 const TargetData * const TD,
9901 const int ix) {
9902 if (!CI->isLosslessCast())
9903 return false;
9904
9905 // The size of ByVal arguments is derived from the type, so we
9906 // can't change to a type with a different size. If the size were
9907 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009908 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009909 return true;
9910
9911 const Type* SrcTy =
9912 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9913 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9914 if (!SrcTy->isSized() || !DstTy->isSized())
9915 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009916 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009917 return false;
9918 return true;
9919}
9920
Chris Lattnera44d8a22003-10-07 22:32:43 +00009921// visitCallSite - Improvements for call and invoke instructions.
9922//
9923Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009924 bool Changed = false;
9925
9926 // If the callee is a constexpr cast of a function, attempt to move the cast
9927 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009928 if (transformConstExprCastCall(CS)) return 0;
9929
Chris Lattner6c266db2003-10-07 22:54:13 +00009930 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009931
Chris Lattner08b22ec2005-05-13 07:09:09 +00009932 if (Function *CalleeF = dyn_cast<Function>(Callee))
9933 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9934 Instruction *OldCall = CS.getInstruction();
9935 // If the call and callee calling conventions don't match, this call must
9936 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009937 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009938 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009939 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009940 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009941 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009942 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9943 return EraseInstFromFunction(*OldCall);
9944 return 0;
9945 }
9946
Chris Lattner17be6352004-10-18 02:59:09 +00009947 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9948 // This instruction is not reachable, just remove it. We insert a store to
9949 // undef so that we know that this code is not reachable, despite the fact
9950 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009951 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009952 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009953 CS.getInstruction());
9954
9955 if (!CS.getInstruction()->use_empty())
9956 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009957 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009958
9959 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9960 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009961 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009962 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009963 }
Chris Lattner17be6352004-10-18 02:59:09 +00009964 return EraseInstFromFunction(*CS.getInstruction());
9965 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009966
Duncan Sandscdb6d922007-09-17 10:26:40 +00009967 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9968 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9969 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9970 return transformCallThroughTrampoline(CS);
9971
Chris Lattner6c266db2003-10-07 22:54:13 +00009972 const PointerType *PTy = cast<PointerType>(Callee->getType());
9973 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9974 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009975 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009976 // See if we can optimize any arguments passed through the varargs area of
9977 // the call.
9978 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009979 E = CS.arg_end(); I != E; ++I, ++ix) {
9980 CastInst *CI = dyn_cast<CastInst>(*I);
9981 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9982 *I = CI->getOperand(0);
9983 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009984 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009985 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009986 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009987
Duncan Sandsf0c33542007-12-19 21:13:37 +00009988 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009989 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009990 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009991 Changed = true;
9992 }
9993
Chris Lattner6c266db2003-10-07 22:54:13 +00009994 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009995}
9996
Chris Lattner9fe38862003-06-19 17:00:31 +00009997// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9998// attempt to move the cast to the arguments of the call/invoke.
9999//
10000bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10001 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10002 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010003 if (CE->getOpcode() != Instruction::BitCast ||
10004 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010005 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010006 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010007 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010008 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010009
10010 // Okay, this is a cast from a function to a different type. Unless doing so
10011 // would cause a type conversion of one of our arguments, change this call to
10012 // be a direct call with arguments casted to the appropriate types.
10013 //
10014 const FunctionType *FT = Callee->getFunctionType();
10015 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010016 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010017
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010018 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010019 return false; // TODO: Handle multiple return values.
10020
Chris Lattnerf78616b2004-01-14 06:06:08 +000010021 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010022 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010023 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010024 // Conversion is ok if changing from one pointer type to another or from
10025 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010026 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010027 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010028 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010029 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010030 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010031
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010032 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010033 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010034 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010035 return false; // Cannot transform this return value.
10036
Chris Lattner58d74912008-03-12 17:45:29 +000010037 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010038 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010039 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010040 return false; // Attribute not compatible with transformed value.
10041 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010042
Chris Lattnerf78616b2004-01-14 06:06:08 +000010043 // If the callsite is an invoke instruction, and the return value is used by
10044 // a PHI node in a successor, we cannot change the return type of the call
10045 // because there is no place to put the cast instruction (without breaking
10046 // the critical edge). Bail out in this case.
10047 if (!Caller->use_empty())
10048 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10049 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10050 UI != E; ++UI)
10051 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10052 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010053 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010054 return false;
10055 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010056
10057 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10058 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010059
Chris Lattner9fe38862003-06-19 17:00:31 +000010060 CallSite::arg_iterator AI = CS.arg_begin();
10061 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10062 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010063 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010064
10065 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010066 return false; // Cannot transform this parameter value.
10067
Devang Patel19c87462008-09-26 22:53:05 +000010068 if (CallerPAL.getParamAttributes(i + 1)
10069 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010070 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010071
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010072 // Converting from one pointer type to another or between a pointer and an
10073 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010074 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010075 (TD && ((isa<PointerType>(ParamTy) ||
10076 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10077 (isa<PointerType>(ActTy) ||
10078 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010079 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010080 }
10081
10082 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010083 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010084 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010085
Chris Lattner58d74912008-03-12 17:45:29 +000010086 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10087 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010088 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010089 // won't be dropping them. Check that these extra arguments have attributes
10090 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010091 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10092 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010093 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010094 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010095 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010096 return false;
10097 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010098
Chris Lattner9fe38862003-06-19 17:00:31 +000010099 // Okay, we decided that this is a safe thing to do: go ahead and start
10100 // inserting cast instructions as necessary...
10101 std::vector<Value*> Args;
10102 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010103 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010104 attrVec.reserve(NumCommonArgs);
10105
10106 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010107 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010108
10109 // If the return value is not being used, the type may not be compatible
10110 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010111 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010112
10113 // Add the new return attributes.
10114 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010115 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010116
10117 AI = CS.arg_begin();
10118 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10119 const Type *ParamTy = FT->getParamType(i);
10120 if ((*AI)->getType() == ParamTy) {
10121 Args.push_back(*AI);
10122 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010123 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010124 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010125 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010126 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010127
10128 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010129 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010130 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010131 }
10132
10133 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010134 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010135 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010136 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010137
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010138 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010139 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010140 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010141 errs() << "WARNING: While resolving call to function '"
10142 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010144 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010145 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10146 const Type *PTy = getPromotedType((*AI)->getType());
10147 if (PTy != (*AI)->getType()) {
10148 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010149 Instruction::CastOps opcode =
10150 CastInst::getCastOpcode(*AI, false, PTy, false);
10151 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010152 } else {
10153 Args.push_back(*AI);
10154 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010155
Duncan Sandse1e520f2008-01-13 08:02:44 +000010156 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010157 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010158 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010159 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010160 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010161 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010162
Devang Patel19c87462008-09-26 22:53:05 +000010163 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10164 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10165
Owen Anderson1d0be152009-08-13 21:58:54 +000010166 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010167 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010168
Eric Christophera66297a2009-07-25 02:45:27 +000010169 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10170 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010171
Chris Lattner9fe38862003-06-19 17:00:31 +000010172 Instruction *NC;
10173 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010174 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010175 Args.begin(), Args.end(),
10176 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010177 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010178 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010179 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010180 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10181 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010182 CallInst *CI = cast<CallInst>(Caller);
10183 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010184 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010185 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010186 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010187 }
10188
Chris Lattner6934a042007-02-11 01:23:03 +000010189 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010190 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010191 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010192 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010193 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010194 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010195 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010196
10197 // If this is an invoke instruction, we should insert it after the first
10198 // non-phi, instruction in the normal successor block.
10199 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010200 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010201 InsertNewInstBefore(NC, *I);
10202 } else {
10203 // Otherwise, it's a call, just insert cast right after the call instr
10204 InsertNewInstBefore(NC, *Caller);
10205 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010206 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010207 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010208 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010209 }
10210 }
10211
Chris Lattner931f8f32009-08-31 05:17:58 +000010212
10213 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010214 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010215
10216 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010217 return true;
10218}
10219
Duncan Sandscdb6d922007-09-17 10:26:40 +000010220// transformCallThroughTrampoline - Turn a call to a function created by the
10221// init_trampoline intrinsic into a direct call to the underlying function.
10222//
10223Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10224 Value *Callee = CS.getCalledValue();
10225 const PointerType *PTy = cast<PointerType>(Callee->getType());
10226 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010227 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010228
10229 // If the call already has the 'nest' attribute somewhere then give up -
10230 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010231 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010232 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010233
10234 IntrinsicInst *Tramp =
10235 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10236
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010237 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010238 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10239 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10240
Devang Patel05988662008-09-25 21:00:45 +000010241 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010242 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010243 unsigned NestIdx = 1;
10244 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010245 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010246
10247 // Look for a parameter marked with the 'nest' attribute.
10248 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10249 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010250 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010251 // Record the parameter type and any other attributes.
10252 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010253 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010254 break;
10255 }
10256
10257 if (NestTy) {
10258 Instruction *Caller = CS.getInstruction();
10259 std::vector<Value*> NewArgs;
10260 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10261
Devang Patel05988662008-09-25 21:00:45 +000010262 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010263 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010264
Duncan Sandscdb6d922007-09-17 10:26:40 +000010265 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010266 // mean appending it. Likewise for attributes.
10267
Devang Patel19c87462008-09-26 22:53:05 +000010268 // Add any result attributes.
10269 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010270 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010271
Duncan Sandscdb6d922007-09-17 10:26:40 +000010272 {
10273 unsigned Idx = 1;
10274 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10275 do {
10276 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010277 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010278 Value *NestVal = Tramp->getOperand(3);
10279 if (NestVal->getType() != NestTy)
10280 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10281 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010282 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010283 }
10284
10285 if (I == E)
10286 break;
10287
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010288 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010289 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010290 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010291 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010292 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010293
10294 ++Idx, ++I;
10295 } while (1);
10296 }
10297
Devang Patel19c87462008-09-26 22:53:05 +000010298 // Add any function attributes.
10299 if (Attributes Attr = Attrs.getFnAttributes())
10300 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10301
Duncan Sandscdb6d922007-09-17 10:26:40 +000010302 // The trampoline may have been bitcast to a bogus type (FTy).
10303 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010304 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010305
Duncan Sandscdb6d922007-09-17 10:26:40 +000010306 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010307 NewTypes.reserve(FTy->getNumParams()+1);
10308
Duncan Sandscdb6d922007-09-17 10:26:40 +000010309 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010310 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010311 {
10312 unsigned Idx = 1;
10313 FunctionType::param_iterator I = FTy->param_begin(),
10314 E = FTy->param_end();
10315
10316 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010317 if (Idx == NestIdx)
10318 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010319 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010320
10321 if (I == E)
10322 break;
10323
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010324 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010325 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010326
10327 ++Idx, ++I;
10328 } while (1);
10329 }
10330
10331 // Replace the trampoline call with a direct call. Let the generic
10332 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010333 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010334 FTy->isVarArg());
10335 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010336 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010337 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010338 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010339 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10340 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010341
10342 Instruction *NewCaller;
10343 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010344 NewCaller = InvokeInst::Create(NewCallee,
10345 II->getNormalDest(), II->getUnwindDest(),
10346 NewArgs.begin(), NewArgs.end(),
10347 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010348 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010349 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010350 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010351 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10352 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353 if (cast<CallInst>(Caller)->isTailCall())
10354 cast<CallInst>(NewCaller)->setTailCall();
10355 cast<CallInst>(NewCaller)->
10356 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010357 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010359 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010360 Caller->replaceAllUsesWith(NewCaller);
10361 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010362 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010363 return 0;
10364 }
10365 }
10366
10367 // Replace the trampoline call with a direct call. Since there is no 'nest'
10368 // parameter, there is no need to adjust the argument list. Let the generic
10369 // code sort out any function type mismatches.
10370 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010371 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010372 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373 CS.setCalledFunction(NewCallee);
10374 return CS.getInstruction();
10375}
10376
Dan Gohman9ad29202009-09-16 16:50:24 +000010377/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10378/// 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 +000010379/// and a single binop.
10380Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10381 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010382 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010383 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010384 Value *LHSVal = FirstInst->getOperand(0);
10385 Value *RHSVal = FirstInst->getOperand(1);
10386
10387 const Type *LHSType = LHSVal->getType();
10388 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010389
Dan Gohman9ad29202009-09-16 16:50:24 +000010390 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010391 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010392 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010393 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010394 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010395 // types or GEP's with different index types.
10396 I->getOperand(0)->getType() != LHSType ||
10397 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010398 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010399
10400 // If they are CmpInst instructions, check their predicates
10401 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10402 if (cast<CmpInst>(I)->getPredicate() !=
10403 cast<CmpInst>(FirstInst)->getPredicate())
10404 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010405
10406 // Keep track of which operand needs a phi node.
10407 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10408 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010409 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010410
10411 // If both LHS and RHS would need a PHI, don't do this transformation,
10412 // because it would increase the number of PHIs entering the block,
10413 // which leads to higher register pressure. This is especially
10414 // bad when the PHIs are in the header of a loop.
10415 if (!LHSVal && !RHSVal)
10416 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010417
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010418 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010419
Chris Lattner7da52b22006-11-01 04:51:18 +000010420 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010421 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010422 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010423 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010424 NewLHS = PHINode::Create(LHSType,
10425 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010426 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10427 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010428 InsertNewInstBefore(NewLHS, PN);
10429 LHSVal = NewLHS;
10430 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010431
10432 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010433 NewRHS = PHINode::Create(RHSType,
10434 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010435 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10436 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010437 InsertNewInstBefore(NewRHS, PN);
10438 RHSVal = NewRHS;
10439 }
10440
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010441 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010442 if (NewLHS || NewRHS) {
10443 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10444 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10445 if (NewLHS) {
10446 Value *NewInLHS = InInst->getOperand(0);
10447 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10448 }
10449 if (NewRHS) {
10450 Value *NewInRHS = InInst->getOperand(1);
10451 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10452 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010453 }
10454 }
10455
Chris Lattner7da52b22006-11-01 04:51:18 +000010456 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010457 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010458 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010459 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010460 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010461}
10462
Chris Lattner05f18922008-12-01 02:34:36 +000010463Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10464 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10465
10466 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10467 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010468 // This is true if all GEP bases are allocas and if all indices into them are
10469 // constants.
10470 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010471
10472 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010473 // more than one phi, which leads to higher register pressure. This is
10474 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010475 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010476
Dan Gohman9ad29202009-09-16 16:50:24 +000010477 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010478 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10479 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10480 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10481 GEP->getNumOperands() != FirstInst->getNumOperands())
10482 return 0;
10483
Chris Lattner36d3e322009-02-21 00:46:50 +000010484 // Keep track of whether or not all GEPs are of alloca pointers.
10485 if (AllBasePointersAreAllocas &&
10486 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10487 !GEP->hasAllConstantIndices()))
10488 AllBasePointersAreAllocas = false;
10489
Chris Lattner05f18922008-12-01 02:34:36 +000010490 // Compare the operand lists.
10491 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10492 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10493 continue;
10494
10495 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10496 // if one of the PHIs has a constant for the index. The index may be
10497 // substantially cheaper to compute for the constants, so making it a
10498 // variable index could pessimize the path. This also handles the case
10499 // for struct indices, which must always be constant.
10500 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10501 isa<ConstantInt>(GEP->getOperand(op)))
10502 return 0;
10503
10504 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10505 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010506
10507 // If we already needed a PHI for an earlier operand, and another operand
10508 // also requires a PHI, we'd be introducing more PHIs than we're
10509 // eliminating, which increases register pressure on entry to the PHI's
10510 // block.
10511 if (NeededPhi)
10512 return 0;
10513
Chris Lattner05f18922008-12-01 02:34:36 +000010514 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010515 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010516 }
10517 }
10518
Chris Lattner36d3e322009-02-21 00:46:50 +000010519 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010520 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010521 // offset calculation, but all the predecessors will have to materialize the
10522 // stack address into a register anyway. We'd actually rather *clone* the
10523 // load up into the predecessors so that we have a load of a gep of an alloca,
10524 // which can usually all be folded into the load.
10525 if (AllBasePointersAreAllocas)
10526 return 0;
10527
Chris Lattner05f18922008-12-01 02:34:36 +000010528 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10529 // that is variable.
10530 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10531
10532 bool HasAnyPHIs = false;
10533 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10534 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10535 Value *FirstOp = FirstInst->getOperand(i);
10536 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10537 FirstOp->getName()+".pn");
10538 InsertNewInstBefore(NewPN, PN);
10539
10540 NewPN->reserveOperandSpace(e);
10541 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10542 OperandPhis[i] = NewPN;
10543 FixedOperands[i] = NewPN;
10544 HasAnyPHIs = true;
10545 }
10546
10547
10548 // Add all operands to the new PHIs.
10549 if (HasAnyPHIs) {
10550 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10551 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10552 BasicBlock *InBB = PN.getIncomingBlock(i);
10553
10554 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10555 if (PHINode *OpPhi = OperandPhis[op])
10556 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10557 }
10558 }
10559
10560 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010561 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10562 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10563 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010564 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10565 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010566}
10567
10568
Chris Lattner21550882009-02-23 05:56:17 +000010569/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10570/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010571/// obvious the value of the load is not changed from the point of the load to
10572/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010573///
10574/// Finally, it is safe, but not profitable, to sink a load targetting a
10575/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10576/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010577static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010578 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10579
10580 for (++BBI; BBI != E; ++BBI)
10581 if (BBI->mayWriteToMemory())
10582 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010583
10584 // Check for non-address taken alloca. If not address-taken already, it isn't
10585 // profitable to do this xform.
10586 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10587 bool isAddressTaken = false;
10588 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10589 UI != E; ++UI) {
10590 if (isa<LoadInst>(UI)) continue;
10591 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10592 // If storing TO the alloca, then the address isn't taken.
10593 if (SI->getOperand(1) == AI) continue;
10594 }
10595 isAddressTaken = true;
10596 break;
10597 }
10598
Chris Lattner36d3e322009-02-21 00:46:50 +000010599 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010600 return false;
10601 }
10602
Chris Lattner36d3e322009-02-21 00:46:50 +000010603 // If this load is a load from a GEP with a constant offset from an alloca,
10604 // then we don't want to sink it. In its present form, it will be
10605 // load [constant stack offset]. Sinking it will cause us to have to
10606 // materialize the stack addresses in each predecessor in a register only to
10607 // do a shared load from register in the successor.
10608 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10609 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10610 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10611 return false;
10612
Chris Lattner76c73142006-11-01 07:13:54 +000010613 return true;
10614}
10615
Chris Lattner9fe38862003-06-19 17:00:31 +000010616
Chris Lattnerbac32862004-11-14 19:13:23 +000010617// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10618// operator and they all are only used by the PHI, PHI together their
10619// inputs, and do the operation once, to the result of the PHI.
10620Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10621 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10622
10623 // Scan the instruction, looking for input operations that can be folded away.
10624 // If all input operands to the phi are the same instruction (e.g. a cast from
10625 // the same type or "+42") we can pull the operation through the PHI, reducing
10626 // code size and simplifying code.
10627 Constant *ConstantOp = 0;
10628 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010629 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010630 if (isa<CastInst>(FirstInst)) {
10631 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010632 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010633 // Can fold binop, compare or shift here if the RHS is a constant,
10634 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010635 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010636 if (ConstantOp == 0)
10637 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010638 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10639 isVolatile = LI->isVolatile();
10640 // We can't sink the load if the loaded value could be modified between the
10641 // load and the PHI.
10642 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010643 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010644 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010645
10646 // If the PHI is of volatile loads and the load block has multiple
10647 // successors, sinking it would remove a load of the volatile value from
10648 // the path through the other successor.
10649 if (isVolatile &&
10650 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10651 return 0;
10652
Chris Lattner9c080502006-11-01 07:43:41 +000010653 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010654 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010655 } else {
10656 return 0; // Cannot fold this operation.
10657 }
10658
10659 // Check to see if all arguments are the same operation.
10660 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10661 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10662 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010663 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010664 return 0;
10665 if (CastSrcTy) {
10666 if (I->getOperand(0)->getType() != CastSrcTy)
10667 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010668 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010669 // We can't sink the load if the loaded value could be modified between
10670 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010671 if (LI->isVolatile() != isVolatile ||
10672 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010673 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010674 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010675
Chris Lattner71042962008-07-08 17:18:32 +000010676 // If the PHI is of volatile loads and the load block has multiple
10677 // successors, sinking it would remove a load of the volatile value from
10678 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010679 if (isVolatile &&
10680 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10681 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010682
Chris Lattnerbac32862004-11-14 19:13:23 +000010683 } else if (I->getOperand(1) != ConstantOp) {
10684 return 0;
10685 }
10686 }
10687
10688 // Okay, they are all the same operation. Create a new PHI node of the
10689 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010690 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10691 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010692 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010693
10694 Value *InVal = FirstInst->getOperand(0);
10695 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010696
10697 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010698 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10699 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10700 if (NewInVal != InVal)
10701 InVal = 0;
10702 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10703 }
10704
10705 Value *PhiVal;
10706 if (InVal) {
10707 // The new PHI unions all of the same values together. This is really
10708 // common, so we handle it intelligently here for compile-time speed.
10709 PhiVal = InVal;
10710 delete NewPN;
10711 } else {
10712 InsertNewInstBefore(NewPN, PN);
10713 PhiVal = NewPN;
10714 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010715
Chris Lattnerbac32862004-11-14 19:13:23 +000010716 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010717 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010718 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010719 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010720 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010721 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010722 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010723 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010724 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10725
10726 // If this was a volatile load that we are merging, make sure to loop through
10727 // and mark all the input loads as non-volatile. If we don't do this, we will
10728 // insert a new volatile load and the old ones will not be deletable.
10729 if (isVolatile)
10730 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10731 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10732
10733 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010734}
Chris Lattnera1be5662002-05-02 17:06:02 +000010735
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010736/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10737/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010738static bool DeadPHICycle(PHINode *PN,
10739 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010740 if (PN->use_empty()) return true;
10741 if (!PN->hasOneUse()) return false;
10742
10743 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010744 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010745 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010746
10747 // Don't scan crazily complex things.
10748 if (PotentiallyDeadPHIs.size() == 16)
10749 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010750
10751 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10752 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010753
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010754 return false;
10755}
10756
Chris Lattnercf5008a2007-11-06 21:52:06 +000010757/// PHIsEqualValue - Return true if this phi node is always equal to
10758/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10759/// z = some value; x = phi (y, z); y = phi (x, z)
10760static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10761 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10762 // See if we already saw this PHI node.
10763 if (!ValueEqualPHIs.insert(PN))
10764 return true;
10765
10766 // Don't scan crazily complex things.
10767 if (ValueEqualPHIs.size() == 16)
10768 return false;
10769
10770 // Scan the operands to see if they are either phi nodes or are equal to
10771 // the value.
10772 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10773 Value *Op = PN->getIncomingValue(i);
10774 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10775 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10776 return false;
10777 } else if (Op != NonPhiInVal)
10778 return false;
10779 }
10780
10781 return true;
10782}
10783
10784
Chris Lattner473945d2002-05-06 18:06:38 +000010785// PHINode simplification
10786//
Chris Lattner7e708292002-06-25 16:13:24 +000010787Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010788 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010789 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010790
Owen Anderson7e057142006-07-10 22:03:18 +000010791 if (Value *V = PN.hasConstantValue())
10792 return ReplaceInstUsesWith(PN, V);
10793
Owen Anderson7e057142006-07-10 22:03:18 +000010794 // If all PHI operands are the same operation, pull them through the PHI,
10795 // reducing code size.
10796 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010797 isa<Instruction>(PN.getIncomingValue(1)) &&
10798 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10799 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10800 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10801 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010802 PN.getIncomingValue(0)->hasOneUse())
10803 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10804 return Result;
10805
10806 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10807 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10808 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010809 if (PN.hasOneUse()) {
10810 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10811 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010812 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010813 PotentiallyDeadPHIs.insert(&PN);
10814 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010815 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010816 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010817
10818 // If this phi has a single use, and if that use just computes a value for
10819 // the next iteration of a loop, delete the phi. This occurs with unused
10820 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10821 // common case here is good because the only other things that catch this
10822 // are induction variable analysis (sometimes) and ADCE, which is only run
10823 // late.
10824 if (PHIUser->hasOneUse() &&
10825 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10826 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010827 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010828 }
10829 }
Owen Anderson7e057142006-07-10 22:03:18 +000010830
Chris Lattnercf5008a2007-11-06 21:52:06 +000010831 // We sometimes end up with phi cycles that non-obviously end up being the
10832 // same value, for example:
10833 // z = some value; x = phi (y, z); y = phi (x, z)
10834 // where the phi nodes don't necessarily need to be in the same block. Do a
10835 // quick check to see if the PHI node only contains a single non-phi value, if
10836 // so, scan to see if the phi cycle is actually equal to that value.
10837 {
10838 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10839 // Scan for the first non-phi operand.
10840 while (InValNo != NumOperandVals &&
10841 isa<PHINode>(PN.getIncomingValue(InValNo)))
10842 ++InValNo;
10843
10844 if (InValNo != NumOperandVals) {
10845 Value *NonPhiInVal = PN.getOperand(InValNo);
10846
10847 // Scan the rest of the operands to see if there are any conflicts, if so
10848 // there is no need to recursively scan other phis.
10849 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10850 Value *OpVal = PN.getIncomingValue(InValNo);
10851 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10852 break;
10853 }
10854
10855 // If we scanned over all operands, then we have one unique value plus
10856 // phi values. Scan PHI nodes to see if they all merge in each other or
10857 // the value.
10858 if (InValNo == NumOperandVals) {
10859 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10860 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10861 return ReplaceInstUsesWith(PN, NonPhiInVal);
10862 }
10863 }
10864 }
Chris Lattner60921c92003-12-19 05:58:40 +000010865 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010866}
10867
Chris Lattner7e708292002-06-25 16:13:24 +000010868Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010869 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010870 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010871 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010872 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010873
Chris Lattnere87597f2004-10-16 18:11:37 +000010874 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010875 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010876
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010877 bool HasZeroPointerIndex = false;
10878 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10879 HasZeroPointerIndex = C->isNullValue();
10880
10881 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010882 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010883
Chris Lattner28977af2004-04-05 01:30:19 +000010884 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010885 if (TD) {
10886 bool MadeChange = false;
10887 unsigned PtrSize = TD->getPointerSizeInBits();
10888
10889 gep_type_iterator GTI = gep_type_begin(GEP);
10890 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10891 I != E; ++I, ++GTI) {
10892 if (!isa<SequentialType>(*GTI)) continue;
10893
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010894 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010895 // to what we need. If narrower, sign-extend it to what we need. This
10896 // explicit cast can make subsequent optimizations more obvious.
10897 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010898 if (OpBits == PtrSize)
10899 continue;
10900
Chris Lattner2345d1d2009-08-30 20:01:10 +000010901 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010902 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010903 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010904 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010905 }
Chris Lattner28977af2004-04-05 01:30:19 +000010906
Chris Lattner90ac28c2002-08-02 19:29:35 +000010907 // Combine Indices - If the source pointer to this getelementptr instruction
10908 // is a getelementptr instruction, combine the indices of the two
10909 // getelementptr instructions into a single instruction.
10910 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010911 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010912 // Note that if our source is a gep chain itself that we wait for that
10913 // chain to be resolved before we perform this transformation. This
10914 // avoids us creating a TON of code in some cases.
10915 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010916 if (GetElementPtrInst *SrcGEP =
10917 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10918 if (SrcGEP->getNumOperands() == 2)
10919 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010920
Chris Lattner72588fc2007-02-15 22:48:32 +000010921 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010922
10923 // Find out whether the last index in the source GEP is a sequential idx.
10924 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010925 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10926 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010927 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010928
Chris Lattner90ac28c2002-08-02 19:29:35 +000010929 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010930 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010931 // Replace: gep (gep %P, long B), long A, ...
10932 // With: T = long A+B; gep %P, T, ...
10933 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010934 Value *Sum;
10935 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10936 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010937 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010938 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010939 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010940 Sum = SO1;
10941 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010942 // If they aren't the same type, then the input hasn't been processed
10943 // by the loop above yet (which canonicalizes sequential index types to
10944 // intptr_t). Just avoid transforming this until the input has been
10945 // normalized.
10946 if (SO1->getType() != GO1->getType())
10947 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010948 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010949 }
Chris Lattner620ce142004-05-07 22:09:22 +000010950
Chris Lattnerab984842009-08-30 05:30:55 +000010951 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010952 if (Src->getNumOperands() == 2) {
10953 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010954 GEP.setOperand(1, Sum);
10955 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010956 }
Chris Lattnerab984842009-08-30 05:30:55 +000010957 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010958 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010959 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010960 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010961 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010962 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010963 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010964 Indices.append(Src->op_begin()+1, Src->op_end());
10965 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010966 }
10967
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010968 if (!Indices.empty())
10969 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10970 Src->isInBounds()) ?
10971 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10972 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010973 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010974 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010975 }
10976
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010977 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10978 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010979 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010980
Chris Lattner2de23192009-08-30 20:38:21 +000010981 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10982 // want to change the gep until the bitcasts are eliminated.
10983 if (getBitCastOperand(X)) {
10984 Worklist.AddValue(PtrOp);
10985 return 0;
10986 }
10987
Chris Lattner963f4ba2009-08-30 20:36:46 +000010988 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10989 // into : GEP [10 x i8]* X, i32 0, ...
10990 //
10991 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10992 // into : GEP i8* X, ...
10993 //
10994 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000010995 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000010996 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10997 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010998 if (const ArrayType *CATy =
10999 dyn_cast<ArrayType>(CPTy->getElementType())) {
11000 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11001 if (CATy->getElementType() == XTy->getElementType()) {
11002 // -> GEP i8* X, ...
11003 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011004 return cast<GEPOperator>(&GEP)->isInBounds() ?
11005 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11006 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011007 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11008 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011009 }
11010
11011 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011012 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011013 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011014 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011015 // At this point, we know that the cast source type is a pointer
11016 // to an array of the same type as the destination pointer
11017 // array. Because the array type is never stepped over (there
11018 // is a leading zero) we can fold the cast into this GEP.
11019 GEP.setOperand(0, X);
11020 return &GEP;
11021 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011022 }
11023 }
Chris Lattnereed48272005-09-13 00:40:14 +000011024 } else if (GEP.getNumOperands() == 2) {
11025 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011026 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11027 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011028 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11029 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011030 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011031 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11032 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011033 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011034 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011035 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011036 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11037 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011038 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011039 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011040 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011041 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011042
11043 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011044 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011045 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011046 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011047
Owen Anderson1d0be152009-08-13 21:58:54 +000011048 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011049 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011050 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011051
11052 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11053 // allow either a mul, shift, or constant here.
11054 Value *NewIdx = 0;
11055 ConstantInt *Scale = 0;
11056 if (ArrayEltSize == 1) {
11057 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011058 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011059 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011060 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011061 Scale = CI;
11062 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11063 if (Inst->getOpcode() == Instruction::Shl &&
11064 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011065 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11066 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011067 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011068 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011069 NewIdx = Inst->getOperand(0);
11070 } else if (Inst->getOpcode() == Instruction::Mul &&
11071 isa<ConstantInt>(Inst->getOperand(1))) {
11072 Scale = cast<ConstantInt>(Inst->getOperand(1));
11073 NewIdx = Inst->getOperand(0);
11074 }
11075 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011076
Chris Lattner7835cdd2005-09-13 18:36:04 +000011077 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011078 // out, perform the transformation. Note, we don't know whether Scale is
11079 // signed or not. We'll use unsigned version of division/modulo
11080 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011081 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011082 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011083 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011084 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011085 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011086 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11087 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011088 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011089 }
11090
11091 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011092 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011093 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011094 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011095 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11096 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11097 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011098 // The NewGEP must be pointer typed, so must the old one -> BitCast
11099 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011100 }
11101 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011102 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011103 }
Chris Lattner58407792009-01-09 04:53:57 +000011104
Chris Lattner46cd5a12009-01-09 05:44:56 +000011105 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011106 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011107 /// Y = gep X, <...constant indices...>
11108 /// into a gep of the original struct. This is important for SROA and alias
11109 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011110 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011111 if (TD &&
11112 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011113 // Determine how much the GEP moves the pointer. We are guaranteed to get
11114 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011115 ConstantInt *OffsetV =
11116 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011117 int64_t Offset = OffsetV->getSExtValue();
11118
11119 // If this GEP instruction doesn't move the pointer, just replace the GEP
11120 // with a bitcast of the real input to the dest type.
11121 if (Offset == 0) {
11122 // If the bitcast is of an allocation, and the allocation will be
11123 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011124 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11125 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011126 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11127 if (Instruction *I = visitBitCast(*BCI)) {
11128 if (I != BCI) {
11129 I->takeName(BCI);
11130 BCI->getParent()->getInstList().insert(BCI, I);
11131 ReplaceInstUsesWith(*BCI, I);
11132 }
11133 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011134 }
Chris Lattner58407792009-01-09 04:53:57 +000011135 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011136 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011137 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011138
11139 // Otherwise, if the offset is non-zero, we need to find out if there is a
11140 // field at Offset in 'A's type. If so, we can pull the cast through the
11141 // GEP.
11142 SmallVector<Value*, 8> NewIndices;
11143 const Type *InTy =
11144 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011145 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011146 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11147 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11148 NewIndices.end()) :
11149 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11150 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011151
11152 if (NGEP->getType() == GEP.getType())
11153 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011154 NGEP->takeName(&GEP);
11155 return new BitCastInst(NGEP, GEP.getType());
11156 }
Chris Lattner58407792009-01-09 04:53:57 +000011157 }
11158 }
11159
Chris Lattner8a2a3112001-12-14 16:52:21 +000011160 return 0;
11161}
11162
Chris Lattner0864acf2002-11-04 16:18:53 +000011163Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11164 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011165 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011166 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11167 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011168 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011169 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011170
11171 // Create and insert the replacement instruction...
11172 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011173 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011174 else {
11175 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011176 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011177 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011178 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011179
Chris Lattner0864acf2002-11-04 16:18:53 +000011180 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011181 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011182 //
11183 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011184 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011185
11186 // Now that I is pointing to the first non-allocation-inst in the block,
11187 // insert our getelementptr instruction...
11188 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011189 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011190 Value *Idx[2];
11191 Idx[0] = NullIdx;
11192 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011193 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11194 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011195
11196 // Now make everything use the getelementptr instead of the original
11197 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011198 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011199 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011200 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011201 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011202 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011203
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011204 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011205 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011206 // Note that we only do this for alloca's, because malloc should allocate
11207 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011208 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011209 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011210
11211 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11212 if (AI.getAlignment() == 0)
11213 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11214 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011215
Chris Lattner0864acf2002-11-04 16:18:53 +000011216 return 0;
11217}
11218
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011219Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11220 Value *Op = FI.getOperand(0);
11221
Chris Lattner17be6352004-10-18 02:59:09 +000011222 // free undef -> unreachable.
11223 if (isa<UndefValue>(Op)) {
11224 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011225 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011226 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011227 return EraseInstFromFunction(FI);
11228 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011229
Chris Lattner6160e852004-02-28 04:57:37 +000011230 // If we have 'free null' delete the instruction. This can happen in stl code
11231 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011232 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011233 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011234
11235 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11236 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11237 FI.setOperand(0, CI->getOperand(0));
11238 return &FI;
11239 }
11240
11241 // Change free (gep X, 0,0,0,0) into free(X)
11242 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11243 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011244 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011245 FI.setOperand(0, GEPI->getOperand(0));
11246 return &FI;
11247 }
11248 }
11249
11250 // Change free(malloc) into nothing, if the malloc has a single use.
11251 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11252 if (MI->hasOneUse()) {
11253 EraseInstFromFunction(FI);
11254 return EraseInstFromFunction(*MI);
11255 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011256 if (isMalloc(Op)) {
11257 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11258 if (Op->hasOneUse() && CI->hasOneUse()) {
11259 EraseInstFromFunction(FI);
11260 EraseInstFromFunction(*CI);
11261 return EraseInstFromFunction(*cast<Instruction>(Op));
11262 }
11263 } else {
11264 // Op is a call to malloc
11265 if (Op->hasOneUse()) {
11266 EraseInstFromFunction(FI);
11267 return EraseInstFromFunction(*cast<Instruction>(Op));
11268 }
11269 }
11270 }
Chris Lattner6160e852004-02-28 04:57:37 +000011271
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011272 return 0;
11273}
11274
11275
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011276/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011277static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011278 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011279 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011280 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011281 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011282
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011283 if (TD) {
11284 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11285 // Instead of loading constant c string, use corresponding integer value
11286 // directly if string length is small enough.
11287 std::string Str;
11288 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11289 unsigned len = Str.length();
11290 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11291 unsigned numBits = Ty->getPrimitiveSizeInBits();
11292 // Replace LI with immediate integer store.
11293 if ((numBits >> 3) == len + 1) {
11294 APInt StrVal(numBits, 0);
11295 APInt SingleChar(numBits, 0);
11296 if (TD->isLittleEndian()) {
11297 for (signed i = len-1; i >= 0; i--) {
11298 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11299 StrVal = (StrVal << 8) | SingleChar;
11300 }
11301 } else {
11302 for (unsigned i = 0; i < len; i++) {
11303 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11304 StrVal = (StrVal << 8) | SingleChar;
11305 }
11306 // Append NULL at the end.
11307 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011308 StrVal = (StrVal << 8) | SingleChar;
11309 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011310 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011311 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011312 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011313 }
11314 }
11315 }
11316
Mon P Wang6753f952009-02-07 22:19:29 +000011317 const PointerType *DestTy = cast<PointerType>(CI->getType());
11318 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011319 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011320
11321 // If the address spaces don't match, don't eliminate the cast.
11322 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11323 return 0;
11324
Chris Lattnerb89e0712004-07-13 01:49:43 +000011325 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011326
Reid Spencer42230162007-01-22 05:51:25 +000011327 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011328 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011329 // If the source is an array, the code below will not succeed. Check to
11330 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11331 // constants.
11332 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11333 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11334 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011335 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011336 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011337 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011338 SrcTy = cast<PointerType>(CastOp->getType());
11339 SrcPTy = SrcTy->getElementType();
11340 }
11341
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011342 if (IC.getTargetData() &&
11343 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011344 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011345 // Do not allow turning this into a load of an integer, which is then
11346 // casted to a pointer, this pessimizes pointer analysis a lot.
11347 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011348 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11349 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011350
Chris Lattnerf9527852005-01-31 04:50:46 +000011351 // Okay, we are casting from one integer or pointer type to another of
11352 // the same size. Instead of casting the pointer before the load, cast
11353 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011354 Value *NewLoad =
11355 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011356 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011357 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011358 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011359 }
11360 }
11361 return 0;
11362}
11363
Chris Lattner833b8a42003-06-26 05:06:25 +000011364Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11365 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011366
Dan Gohman9941f742007-07-20 16:34:21 +000011367 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011368 if (TD) {
11369 unsigned KnownAlign =
11370 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11371 if (KnownAlign >
11372 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11373 LI.getAlignment()))
11374 LI.setAlignment(KnownAlign);
11375 }
Dan Gohman9941f742007-07-20 16:34:21 +000011376
Chris Lattner963f4ba2009-08-30 20:36:46 +000011377 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011378 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011379 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011380 return Res;
11381
11382 // None of the following transforms are legal for volatile loads.
11383 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011384
Dan Gohman2276a7b2008-10-15 23:19:35 +000011385 // Do really simple store-to-load forwarding and load CSE, to catch cases
11386 // where there are several consequtive memory accesses to the same location,
11387 // separated by a few arithmetic operations.
11388 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011389 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11390 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011391
Christopher Lambb15147e2007-12-29 07:56:53 +000011392 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11393 const Value *GEPI0 = GEPI->getOperand(0);
11394 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011395 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011396 // Insert a new store to null instruction before the load to indicate
11397 // that this code is not reachable. We do this instead of inserting
11398 // an unreachable instruction directly because we cannot modify the
11399 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011400 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011401 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011402 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011403 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011404 }
Chris Lattner37366c12005-05-01 04:24:53 +000011405
Chris Lattnere87597f2004-10-16 18:11:37 +000011406 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011407 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011408 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011409 if (isa<UndefValue>(C) ||
11410 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011411 // Insert a new store to null instruction before the load to indicate that
11412 // this code is not reachable. We do this instead of inserting an
11413 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011414 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011415 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011416 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011417 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011418
Chris Lattnere87597f2004-10-16 18:11:37 +000011419 // Instcombine load (constant global) into the value loaded.
11420 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011421 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011422 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011423
Chris Lattnere87597f2004-10-16 18:11:37 +000011424 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011425 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011426 if (CE->getOpcode() == Instruction::GetElementPtr) {
11427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011428 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011429 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011430 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011431 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011432 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011433 if (CE->getOperand(0)->isNullValue()) {
11434 // Insert a new store to null instruction before the load to indicate
11435 // that this code is not reachable. We do this instead of inserting
11436 // an unreachable instruction directly because we cannot modify the
11437 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011438 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011439 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011440 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011441 }
11442
Reid Spencer3da59db2006-11-27 01:05:10 +000011443 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011444 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011445 return Res;
11446 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011447 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011448 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011449
11450 // If this load comes from anywhere in a constant global, and if the global
11451 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011452 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011453 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011454 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011455 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011456 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011457 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011458 }
11459 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011460
Chris Lattner37366c12005-05-01 04:24:53 +000011461 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011462 // Change select and PHI nodes to select values instead of addresses: this
11463 // helps alias analysis out a lot, allows many others simplifications, and
11464 // exposes redundancy in the code.
11465 //
11466 // Note that we cannot do the transformation unless we know that the
11467 // introduced loads cannot trap! Something like this is valid as long as
11468 // the condition is always false: load (select bool %C, int* null, int* %G),
11469 // but it would not be valid if we transformed it to load from null
11470 // unconditionally.
11471 //
11472 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11473 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011474 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11475 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011476 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11477 SI->getOperand(1)->getName()+".val");
11478 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11479 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011480 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011481 }
11482
Chris Lattner684fe212004-09-23 15:46:00 +000011483 // load (select (cond, null, P)) -> load P
11484 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11485 if (C->isNullValue()) {
11486 LI.setOperand(0, SI->getOperand(2));
11487 return &LI;
11488 }
11489
11490 // load (select (cond, P, null)) -> load P
11491 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11492 if (C->isNullValue()) {
11493 LI.setOperand(0, SI->getOperand(1));
11494 return &LI;
11495 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011496 }
11497 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011498 return 0;
11499}
11500
Reid Spencer55af2b52007-01-19 21:20:31 +000011501/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011502/// when possible. This makes it generally easy to do alias analysis and/or
11503/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011504static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11505 User *CI = cast<User>(SI.getOperand(1));
11506 Value *CastOp = CI->getOperand(0);
11507
11508 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011509 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11510 if (SrcTy == 0) return 0;
11511
11512 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011513
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011514 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11515 return 0;
11516
Chris Lattner3914f722009-01-24 01:00:13 +000011517 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11518 /// to its first element. This allows us to handle things like:
11519 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11520 /// on 32-bit hosts.
11521 SmallVector<Value*, 4> NewGEPIndices;
11522
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011523 // If the source is an array, the code below will not succeed. Check to
11524 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11525 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011526 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11527 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011528 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011529 NewGEPIndices.push_back(Zero);
11530
11531 while (1) {
11532 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011533 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011534 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011535 NewGEPIndices.push_back(Zero);
11536 SrcPTy = STy->getElementType(0);
11537 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11538 NewGEPIndices.push_back(Zero);
11539 SrcPTy = ATy->getElementType();
11540 } else {
11541 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011542 }
Chris Lattner3914f722009-01-24 01:00:13 +000011543 }
11544
Owen Andersondebcb012009-07-29 22:17:13 +000011545 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011546 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011547
11548 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11549 return 0;
11550
Chris Lattner71759c42009-01-16 20:12:52 +000011551 // If the pointers point into different address spaces or if they point to
11552 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011553 if (!IC.getTargetData() ||
11554 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011555 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011556 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11557 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011558 return 0;
11559
11560 // Okay, we are casting from one integer or pointer type to another of
11561 // the same size. Instead of casting the pointer before
11562 // the store, cast the value to be stored.
11563 Value *NewCast;
11564 Value *SIOp0 = SI.getOperand(0);
11565 Instruction::CastOps opcode = Instruction::BitCast;
11566 const Type* CastSrcTy = SIOp0->getType();
11567 const Type* CastDstTy = SrcPTy;
11568 if (isa<PointerType>(CastDstTy)) {
11569 if (CastSrcTy->isInteger())
11570 opcode = Instruction::IntToPtr;
11571 } else if (isa<IntegerType>(CastDstTy)) {
11572 if (isa<PointerType>(SIOp0->getType()))
11573 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011574 }
Chris Lattner3914f722009-01-24 01:00:13 +000011575
11576 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11577 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011578 if (!NewGEPIndices.empty())
11579 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11580 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011581
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011582 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11583 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011584 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011585}
11586
Chris Lattner4aebaee2008-11-27 08:56:30 +000011587/// equivalentAddressValues - Test if A and B will obviously have the same
11588/// value. This includes recognizing that %t0 and %t1 will have the same
11589/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011590/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011591/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011592/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011593/// %t2 = load i32* %t1
11594///
11595static bool equivalentAddressValues(Value *A, Value *B) {
11596 // Test if the values are trivially equivalent.
11597 if (A == B) return true;
11598
11599 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011600 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11601 // its only used to compare two uses within the same basic block, which
11602 // means that they'll always either have the same value or one of them
11603 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011604 if (isa<BinaryOperator>(A) ||
11605 isa<CastInst>(A) ||
11606 isa<PHINode>(A) ||
11607 isa<GetElementPtrInst>(A))
11608 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011609 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011610 return true;
11611
11612 // Otherwise they may not be equivalent.
11613 return false;
11614}
11615
Dale Johannesen4945c652009-03-03 21:26:39 +000011616// If this instruction has two uses, one of which is a llvm.dbg.declare,
11617// return the llvm.dbg.declare.
11618DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11619 if (!V->hasNUses(2))
11620 return 0;
11621 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11622 UI != E; ++UI) {
11623 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11624 return DI;
11625 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11626 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11627 return DI;
11628 }
11629 }
11630 return 0;
11631}
11632
Chris Lattner2f503e62005-01-31 05:36:43 +000011633Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11634 Value *Val = SI.getOperand(0);
11635 Value *Ptr = SI.getOperand(1);
11636
11637 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011638 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011639 ++NumCombined;
11640 return 0;
11641 }
Chris Lattner836692d2007-01-15 06:51:56 +000011642
11643 // If the RHS is an alloca with a single use, zapify the store, making the
11644 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011645 // If the RHS is an alloca with a two uses, the other one being a
11646 // llvm.dbg.declare, zapify the store and the declare, making the
11647 // alloca dead. We must do this to prevent declare's from affecting
11648 // codegen.
11649 if (!SI.isVolatile()) {
11650 if (Ptr->hasOneUse()) {
11651 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011652 EraseInstFromFunction(SI);
11653 ++NumCombined;
11654 return 0;
11655 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011656 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11657 if (isa<AllocaInst>(GEP->getOperand(0))) {
11658 if (GEP->getOperand(0)->hasOneUse()) {
11659 EraseInstFromFunction(SI);
11660 ++NumCombined;
11661 return 0;
11662 }
11663 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11664 EraseInstFromFunction(*DI);
11665 EraseInstFromFunction(SI);
11666 ++NumCombined;
11667 return 0;
11668 }
11669 }
11670 }
11671 }
11672 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11673 EraseInstFromFunction(*DI);
11674 EraseInstFromFunction(SI);
11675 ++NumCombined;
11676 return 0;
11677 }
Chris Lattner836692d2007-01-15 06:51:56 +000011678 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011679
Dan Gohman9941f742007-07-20 16:34:21 +000011680 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011681 if (TD) {
11682 unsigned KnownAlign =
11683 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11684 if (KnownAlign >
11685 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11686 SI.getAlignment()))
11687 SI.setAlignment(KnownAlign);
11688 }
Dan Gohman9941f742007-07-20 16:34:21 +000011689
Dale Johannesenacb51a32009-03-03 01:43:03 +000011690 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011691 // stores to the same location, separated by a few arithmetic operations. This
11692 // situation often occurs with bitfield accesses.
11693 BasicBlock::iterator BBI = &SI;
11694 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11695 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011696 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011697 // Don't count debug info directives, lest they affect codegen,
11698 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11699 // It is necessary for correctness to skip those that feed into a
11700 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011701 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011702 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011703 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011704 continue;
11705 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011706
11707 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11708 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011709 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11710 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011711 ++NumDeadStore;
11712 ++BBI;
11713 EraseInstFromFunction(*PrevSI);
11714 continue;
11715 }
11716 break;
11717 }
11718
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011719 // If this is a load, we have to stop. However, if the loaded value is from
11720 // the pointer we're loading and is producing the pointer we're storing,
11721 // then *this* store is dead (X = load P; store X -> P).
11722 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011723 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11724 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011725 EraseInstFromFunction(SI);
11726 ++NumCombined;
11727 return 0;
11728 }
11729 // Otherwise, this is a load from some other location. Stores before it
11730 // may not be dead.
11731 break;
11732 }
11733
Chris Lattner9ca96412006-02-08 03:25:32 +000011734 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011735 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011736 break;
11737 }
11738
11739
11740 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011741
11742 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011743 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011744 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011745 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011746 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011747 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011748 ++NumCombined;
11749 }
11750 return 0; // Do not modify these!
11751 }
11752
11753 // store undef, Ptr -> noop
11754 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011755 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011756 ++NumCombined;
11757 return 0;
11758 }
11759
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011760 // If the pointer destination is a cast, see if we can fold the cast into the
11761 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011762 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011763 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11764 return Res;
11765 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011766 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011767 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11768 return Res;
11769
Chris Lattner408902b2005-09-12 23:23:25 +000011770
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011771 // If this store is the last instruction in the basic block (possibly
11772 // excepting debug info instructions and the pointer bitcasts that feed
11773 // into them), and if the block ends with an unconditional branch, try
11774 // to move it to the successor block.
11775 BBI = &SI;
11776 do {
11777 ++BBI;
11778 } while (isa<DbgInfoIntrinsic>(BBI) ||
11779 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011780 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011781 if (BI->isUnconditional())
11782 if (SimplifyStoreAtEndOfBlock(SI))
11783 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011784
Chris Lattner2f503e62005-01-31 05:36:43 +000011785 return 0;
11786}
11787
Chris Lattner3284d1f2007-04-15 00:07:55 +000011788/// SimplifyStoreAtEndOfBlock - Turn things like:
11789/// if () { *P = v1; } else { *P = v2 }
11790/// into a phi node with a store in the successor.
11791///
Chris Lattner31755a02007-04-15 01:02:18 +000011792/// Simplify things like:
11793/// *P = v1; if () { *P = v2; }
11794/// into a phi node with a store in the successor.
11795///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011796bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11797 BasicBlock *StoreBB = SI.getParent();
11798
11799 // Check to see if the successor block has exactly two incoming edges. If
11800 // so, see if the other predecessor contains a store to the same location.
11801 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011802 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011803
11804 // Determine whether Dest has exactly two predecessors and, if so, compute
11805 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011806 pred_iterator PI = pred_begin(DestBB);
11807 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011808 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011809 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011810 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011811 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011812 return false;
11813
11814 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011815 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011816 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011817 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011818 }
Chris Lattner31755a02007-04-15 01:02:18 +000011819 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011820 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011821
11822 // Bail out if all the relevant blocks aren't distinct (this can happen,
11823 // for example, if SI is in an infinite loop)
11824 if (StoreBB == DestBB || OtherBB == DestBB)
11825 return false;
11826
Chris Lattner31755a02007-04-15 01:02:18 +000011827 // Verify that the other block ends in a branch and is not otherwise empty.
11828 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011829 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011830 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011831 return false;
11832
Chris Lattner31755a02007-04-15 01:02:18 +000011833 // If the other block ends in an unconditional branch, check for the 'if then
11834 // else' case. there is an instruction before the branch.
11835 StoreInst *OtherStore = 0;
11836 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011837 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011838 // Skip over debugging info.
11839 while (isa<DbgInfoIntrinsic>(BBI) ||
11840 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11841 if (BBI==OtherBB->begin())
11842 return false;
11843 --BBI;
11844 }
11845 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011846 OtherStore = dyn_cast<StoreInst>(BBI);
11847 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11848 return false;
11849 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011850 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011851 // destinations is StoreBB, then we have the if/then case.
11852 if (OtherBr->getSuccessor(0) != StoreBB &&
11853 OtherBr->getSuccessor(1) != StoreBB)
11854 return false;
11855
11856 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011857 // if/then triangle. See if there is a store to the same ptr as SI that
11858 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011859 for (;; --BBI) {
11860 // Check to see if we find the matching store.
11861 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11862 if (OtherStore->getOperand(1) != SI.getOperand(1))
11863 return false;
11864 break;
11865 }
Eli Friedman6903a242008-06-13 22:02:12 +000011866 // If we find something that may be using or overwriting the stored
11867 // value, or if we run out of instructions, we can't do the xform.
11868 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011869 BBI == OtherBB->begin())
11870 return false;
11871 }
11872
11873 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011874 // make sure nothing reads or overwrites the stored value in
11875 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011876 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11877 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011878 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011879 return false;
11880 }
11881 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011882
Chris Lattner31755a02007-04-15 01:02:18 +000011883 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011884 Value *MergedVal = OtherStore->getOperand(0);
11885 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011886 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011887 PN->reserveOperandSpace(2);
11888 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011889 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11890 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011891 }
11892
11893 // Advance to a place where it is safe to insert the new store and
11894 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011895 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011896 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11897 OtherStore->isVolatile()), *BBI);
11898
11899 // Nuke the old stores.
11900 EraseInstFromFunction(SI);
11901 EraseInstFromFunction(*OtherStore);
11902 ++NumCombined;
11903 return true;
11904}
11905
Chris Lattner2f503e62005-01-31 05:36:43 +000011906
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011907Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11908 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011909 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011910 BasicBlock *TrueDest;
11911 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011912 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011913 !isa<Constant>(X)) {
11914 // Swap Destinations and condition...
11915 BI.setCondition(X);
11916 BI.setSuccessor(0, FalseDest);
11917 BI.setSuccessor(1, TrueDest);
11918 return &BI;
11919 }
11920
Reid Spencere4d87aa2006-12-23 06:05:41 +000011921 // Cannonicalize fcmp_one -> fcmp_oeq
11922 FCmpInst::Predicate FPred; Value *Y;
11923 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011924 TrueDest, FalseDest)) &&
11925 BI.getCondition()->hasOneUse())
11926 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11927 FPred == FCmpInst::FCMP_OGE) {
11928 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11929 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11930
11931 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011932 BI.setSuccessor(0, FalseDest);
11933 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011934 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011935 return &BI;
11936 }
11937
11938 // Cannonicalize icmp_ne -> icmp_eq
11939 ICmpInst::Predicate IPred;
11940 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011941 TrueDest, FalseDest)) &&
11942 BI.getCondition()->hasOneUse())
11943 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11944 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11945 IPred == ICmpInst::ICMP_SGE) {
11946 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11947 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11948 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011949 BI.setSuccessor(0, FalseDest);
11950 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011951 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011952 return &BI;
11953 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011954
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011955 return 0;
11956}
Chris Lattner0864acf2002-11-04 16:18:53 +000011957
Chris Lattner46238a62004-07-03 00:26:11 +000011958Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11959 Value *Cond = SI.getCondition();
11960 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11961 if (I->getOpcode() == Instruction::Add)
11962 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11963 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11964 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011965 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011966 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011967 AddRHS));
11968 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011969 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011970 return &SI;
11971 }
11972 }
11973 return 0;
11974}
11975
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011976Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011977 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011978
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011979 if (!EV.hasIndices())
11980 return ReplaceInstUsesWith(EV, Agg);
11981
11982 if (Constant *C = dyn_cast<Constant>(Agg)) {
11983 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011984 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011985
11986 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011987 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011988
11989 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11990 // Extract the element indexed by the first index out of the constant
11991 Value *V = C->getOperand(*EV.idx_begin());
11992 if (EV.getNumIndices() > 1)
11993 // Extract the remaining indices out of the constant indexed by the
11994 // first index
11995 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11996 else
11997 return ReplaceInstUsesWith(EV, V);
11998 }
11999 return 0; // Can't handle other constants
12000 }
12001 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12002 // We're extracting from an insertvalue instruction, compare the indices
12003 const unsigned *exti, *exte, *insi, *inse;
12004 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12005 exte = EV.idx_end(), inse = IV->idx_end();
12006 exti != exte && insi != inse;
12007 ++exti, ++insi) {
12008 if (*insi != *exti)
12009 // The insert and extract both reference distinctly different elements.
12010 // This means the extract is not influenced by the insert, and we can
12011 // replace the aggregate operand of the extract with the aggregate
12012 // operand of the insert. i.e., replace
12013 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12014 // %E = extractvalue { i32, { i32 } } %I, 0
12015 // with
12016 // %E = extractvalue { i32, { i32 } } %A, 0
12017 return ExtractValueInst::Create(IV->getAggregateOperand(),
12018 EV.idx_begin(), EV.idx_end());
12019 }
12020 if (exti == exte && insi == inse)
12021 // Both iterators are at the end: Index lists are identical. Replace
12022 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12023 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12024 // with "i32 42"
12025 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12026 if (exti == exte) {
12027 // The extract list is a prefix of the insert list. i.e. replace
12028 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12029 // %E = extractvalue { i32, { i32 } } %I, 1
12030 // with
12031 // %X = extractvalue { i32, { i32 } } %A, 1
12032 // %E = insertvalue { i32 } %X, i32 42, 0
12033 // by switching the order of the insert and extract (though the
12034 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012035 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12036 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012037 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12038 insi, inse);
12039 }
12040 if (insi == inse)
12041 // The insert list is a prefix of the extract list
12042 // We can simply remove the common indices from the extract and make it
12043 // operate on the inserted value instead of the insertvalue result.
12044 // i.e., replace
12045 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12046 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12047 // with
12048 // %E extractvalue { i32 } { i32 42 }, 0
12049 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12050 exti, exte);
12051 }
12052 // Can't simplify extracts from other values. Note that nested extracts are
12053 // already simplified implicitely by the above (extract ( extract (insert) )
12054 // will be translated into extract ( insert ( extract ) ) first and then just
12055 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012056 return 0;
12057}
12058
Chris Lattner220b0cf2006-03-05 00:22:33 +000012059/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12060/// is to leave as a vector operation.
12061static bool CheapToScalarize(Value *V, bool isConstant) {
12062 if (isa<ConstantAggregateZero>(V))
12063 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012064 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012065 if (isConstant) return true;
12066 // If all elts are the same, we can extract.
12067 Constant *Op0 = C->getOperand(0);
12068 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12069 if (C->getOperand(i) != Op0)
12070 return false;
12071 return true;
12072 }
12073 Instruction *I = dyn_cast<Instruction>(V);
12074 if (!I) return false;
12075
12076 // Insert element gets simplified to the inserted element or is deleted if
12077 // this is constant idx extract element and its a constant idx insertelt.
12078 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12079 isa<ConstantInt>(I->getOperand(2)))
12080 return true;
12081 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12082 return true;
12083 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12084 if (BO->hasOneUse() &&
12085 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12086 CheapToScalarize(BO->getOperand(1), isConstant)))
12087 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012088 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12089 if (CI->hasOneUse() &&
12090 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12091 CheapToScalarize(CI->getOperand(1), isConstant)))
12092 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012093
12094 return false;
12095}
12096
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012097/// Read and decode a shufflevector mask.
12098///
12099/// It turns undef elements into values that are larger than the number of
12100/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012101static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12102 unsigned NElts = SVI->getType()->getNumElements();
12103 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12104 return std::vector<unsigned>(NElts, 0);
12105 if (isa<UndefValue>(SVI->getOperand(2)))
12106 return std::vector<unsigned>(NElts, 2*NElts);
12107
12108 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012109 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012110 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12111 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012112 Result.push_back(NElts*2); // undef -> 8
12113 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012114 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012115 return Result;
12116}
12117
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012118/// FindScalarElement - Given a vector and an element number, see if the scalar
12119/// value is already around as a register, for example if it were inserted then
12120/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012121static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012122 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012123 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12124 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012125 unsigned Width = PTy->getNumElements();
12126 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012127 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012128
12129 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012130 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012131 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012132 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012133 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012134 return CP->getOperand(EltNo);
12135 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12136 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012137 if (!isa<ConstantInt>(III->getOperand(2)))
12138 return 0;
12139 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012140
12141 // If this is an insert to the element we are looking for, return the
12142 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012143 if (EltNo == IIElt)
12144 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012145
12146 // Otherwise, the insertelement doesn't modify the value, recurse on its
12147 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012148 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012149 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012150 unsigned LHSWidth =
12151 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012152 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012153 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012154 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012155 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012156 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012157 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012158 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012159 }
12160
12161 // Otherwise, we don't know.
12162 return 0;
12163}
12164
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012165Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012166 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012167 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012168 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012169
Dan Gohman07a96762007-07-16 14:29:03 +000012170 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012171 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012172 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012173
Reid Spencer9d6565a2007-02-15 02:26:10 +000012174 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012175 // If vector val is constant with all elements the same, replace EI with
12176 // that element. When the elements are not identical, we cannot replace yet
12177 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012178 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012179 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012180 if (C->getOperand(i) != op0) {
12181 op0 = 0;
12182 break;
12183 }
12184 if (op0)
12185 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012186 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012187
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012188 // If extracting a specified index from the vector, see if we can recursively
12189 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012190 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012191 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012192 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012193
12194 // If this is extracting an invalid index, turn this into undef, to avoid
12195 // crashing the code below.
12196 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012197 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012198
Chris Lattner867b99f2006-10-05 06:55:50 +000012199 // This instruction only demands the single element from the input vector.
12200 // If the input vector has a single use, simplify it based on this use
12201 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012202 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012203 APInt UndefElts(VectorWidth, 0);
12204 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012205 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012206 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012207 EI.setOperand(0, V);
12208 return &EI;
12209 }
12210 }
12211
Owen Andersond672ecb2009-07-03 00:17:18 +000012212 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012213 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012214
12215 // If the this extractelement is directly using a bitcast from a vector of
12216 // the same number of elements, see if we can find the source element from
12217 // it. In this case, we will end up needing to bitcast the scalars.
12218 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12219 if (const VectorType *VT =
12220 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12221 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012222 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12223 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012224 return new BitCastInst(Elt, EI.getType());
12225 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012226 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012227
Chris Lattner73fa49d2006-05-25 22:53:38 +000012228 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012229 // Push extractelement into predecessor operation if legal and
12230 // profitable to do so
12231 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12232 if (I->hasOneUse() &&
12233 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12234 Value *newEI0 =
12235 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12236 EI.getName()+".lhs");
12237 Value *newEI1 =
12238 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12239 EI.getName()+".rhs");
12240 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012241 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012242 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012243 // Extracting the inserted element?
12244 if (IE->getOperand(2) == EI.getOperand(1))
12245 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12246 // If the inserted and extracted elements are constants, they must not
12247 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012248 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012249 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012250 EI.setOperand(0, IE->getOperand(0));
12251 return &EI;
12252 }
12253 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12254 // If this is extracting an element from a shufflevector, figure out where
12255 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012256 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12257 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012258 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012259 unsigned LHSWidth =
12260 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12261
12262 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012263 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012264 else if (SrcIdx < LHSWidth*2) {
12265 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012266 Src = SVI->getOperand(1);
12267 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012268 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012269 }
Eric Christophera3500da2009-07-25 02:28:41 +000012270 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012271 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12272 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012273 }
12274 }
Eli Friedman2451a642009-07-18 23:06:53 +000012275 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012276 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012277 return 0;
12278}
12279
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012280/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12281/// elements from either LHS or RHS, return the shuffle mask and true.
12282/// Otherwise, return false.
12283static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012284 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012285 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012286 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12287 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012288 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012289
12290 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012291 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012292 return true;
12293 } else if (V == LHS) {
12294 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012295 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012296 return true;
12297 } else if (V == RHS) {
12298 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012299 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012300 return true;
12301 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12302 // If this is an insert of an extract from some other vector, include it.
12303 Value *VecOp = IEI->getOperand(0);
12304 Value *ScalarOp = IEI->getOperand(1);
12305 Value *IdxOp = IEI->getOperand(2);
12306
Chris Lattnerd929f062006-04-27 21:14:21 +000012307 if (!isa<ConstantInt>(IdxOp))
12308 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012309 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012310
12311 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12312 // Okay, we can handle this if the vector we are insertinting into is
12313 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012314 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012315 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012316 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012317 return true;
12318 }
12319 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12320 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012321 EI->getOperand(0)->getType() == V->getType()) {
12322 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012323 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012324
12325 // This must be extracting from either LHS or RHS.
12326 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12327 // Okay, we can handle this if the vector we are insertinting into is
12328 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012329 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012330 // If so, update the mask to reflect the inserted value.
12331 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012332 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012333 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012334 } else {
12335 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012336 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012337 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012338
12339 }
12340 return true;
12341 }
12342 }
12343 }
12344 }
12345 }
12346 // TODO: Handle shufflevector here!
12347
12348 return false;
12349}
12350
12351/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12352/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12353/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012354static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012355 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012356 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012357 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012358 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012359 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012360
12361 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012362 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012363 return V;
12364 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012365 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012366 return V;
12367 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12368 // If this is an insert of an extract from some other vector, include it.
12369 Value *VecOp = IEI->getOperand(0);
12370 Value *ScalarOp = IEI->getOperand(1);
12371 Value *IdxOp = IEI->getOperand(2);
12372
12373 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12374 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12375 EI->getOperand(0)->getType() == V->getType()) {
12376 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012377 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12378 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012379
12380 // Either the extracted from or inserted into vector must be RHSVec,
12381 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012382 if (EI->getOperand(0) == RHS || RHS == 0) {
12383 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012384 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012385 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012386 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012387 return V;
12388 }
12389
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012390 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012391 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12392 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012393 // Everything but the extracted element is replaced with the RHS.
12394 for (unsigned i = 0; i != NumElts; ++i) {
12395 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012396 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012397 }
12398 return V;
12399 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012400
12401 // If this insertelement is a chain that comes from exactly these two
12402 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012403 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12404 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012405 return EI->getOperand(0);
12406
Chris Lattnerefb47352006-04-15 01:39:45 +000012407 }
12408 }
12409 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012410 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012411
12412 // Otherwise, can't do anything fancy. Return an identity vector.
12413 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012414 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012415 return V;
12416}
12417
12418Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12419 Value *VecOp = IE.getOperand(0);
12420 Value *ScalarOp = IE.getOperand(1);
12421 Value *IdxOp = IE.getOperand(2);
12422
Chris Lattner599ded12007-04-09 01:11:16 +000012423 // Inserting an undef or into an undefined place, remove this.
12424 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12425 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012426
Chris Lattnerefb47352006-04-15 01:39:45 +000012427 // If the inserted element was extracted from some other vector, and if the
12428 // indexes are constant, try to turn this into a shufflevector operation.
12429 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12430 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12431 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012432 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012433 unsigned ExtractedIdx =
12434 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012435 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012436
12437 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12438 return ReplaceInstUsesWith(IE, VecOp);
12439
12440 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012441 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012442
12443 // If we are extracting a value from a vector, then inserting it right
12444 // back into the same place, just use the input vector.
12445 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12446 return ReplaceInstUsesWith(IE, VecOp);
12447
12448 // We could theoretically do this for ANY input. However, doing so could
12449 // turn chains of insertelement instructions into a chain of shufflevector
12450 // instructions, and right now we do not merge shufflevectors. As such,
12451 // only do this in a situation where it is clear that there is benefit.
12452 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12453 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12454 // the values of VecOp, except then one read from EIOp0.
12455 // Build a new shuffle mask.
12456 std::vector<Constant*> Mask;
12457 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012458 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012459 else {
12460 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012461 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012462 NumVectorElts));
12463 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012464 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012465 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012466 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012467 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012468 }
12469
12470 // If this insertelement isn't used by some other insertelement, turn it
12471 // (and any insertelements it points to), into one big shuffle.
12472 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12473 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012474 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012475 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012476 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012477 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012478 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012479 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012480 }
12481 }
12482 }
12483
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012484 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12485 APInt UndefElts(VWidth, 0);
12486 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12487 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12488 return &IE;
12489
Chris Lattnerefb47352006-04-15 01:39:45 +000012490 return 0;
12491}
12492
12493
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012494Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12495 Value *LHS = SVI.getOperand(0);
12496 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012497 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012498
12499 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012500
Chris Lattner867b99f2006-10-05 06:55:50 +000012501 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012502 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012503 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012504
Dan Gohman488fbfc2008-09-09 18:11:14 +000012505 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012506
12507 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12508 return 0;
12509
Evan Cheng388df622009-02-03 10:05:09 +000012510 APInt UndefElts(VWidth, 0);
12511 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12512 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012513 LHS = SVI.getOperand(0);
12514 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012515 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012516 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012517
Chris Lattner863bcff2006-05-25 23:48:38 +000012518 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12519 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12520 if (LHS == RHS || isa<UndefValue>(LHS)) {
12521 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012522 // shuffle(undef,undef,mask) -> undef.
12523 return ReplaceInstUsesWith(SVI, LHS);
12524 }
12525
Chris Lattner863bcff2006-05-25 23:48:38 +000012526 // Remap any references to RHS to use LHS.
12527 std::vector<Constant*> Elts;
12528 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012529 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012530 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012531 else {
12532 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012533 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012534 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012535 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012536 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012537 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012538 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012539 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012540 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012541 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012542 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012543 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012544 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012545 LHS = SVI.getOperand(0);
12546 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012547 MadeChange = true;
12548 }
12549
Chris Lattner7b2e27922006-05-26 00:29:06 +000012550 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012551 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012552
Chris Lattner863bcff2006-05-25 23:48:38 +000012553 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12554 if (Mask[i] >= e*2) continue; // Ignore undef values.
12555 // Is this an identity shuffle of the LHS value?
12556 isLHSID &= (Mask[i] == i);
12557
12558 // Is this an identity shuffle of the RHS value?
12559 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012560 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012561
Chris Lattner863bcff2006-05-25 23:48:38 +000012562 // Eliminate identity shuffles.
12563 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12564 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012565
Chris Lattner7b2e27922006-05-26 00:29:06 +000012566 // If the LHS is a shufflevector itself, see if we can combine it with this
12567 // one without producing an unusual shuffle. Here we are really conservative:
12568 // we are absolutely afraid of producing a shuffle mask not in the input
12569 // program, because the code gen may not be smart enough to turn a merged
12570 // shuffle into two specific shuffles: it may produce worse code. As such,
12571 // we only merge two shuffles if the result is one of the two input shuffle
12572 // masks. In this case, merging the shuffles just removes one instruction,
12573 // which we know is safe. This is good for things like turning:
12574 // (splat(splat)) -> splat.
12575 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12576 if (isa<UndefValue>(RHS)) {
12577 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12578
12579 std::vector<unsigned> NewMask;
12580 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12581 if (Mask[i] >= 2*e)
12582 NewMask.push_back(2*e);
12583 else
12584 NewMask.push_back(LHSMask[Mask[i]]);
12585
12586 // If the result mask is equal to the src shuffle or this shuffle mask, do
12587 // the replacement.
12588 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012589 unsigned LHSInNElts =
12590 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012591 std::vector<Constant*> Elts;
12592 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012593 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012594 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012595 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012596 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012597 }
12598 }
12599 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12600 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012601 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012602 }
12603 }
12604 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012605
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012606 return MadeChange ? &SVI : 0;
12607}
12608
12609
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012610
Chris Lattnerea1c4542004-12-08 23:43:58 +000012611
12612/// TryToSinkInstruction - Try to move the specified instruction from its
12613/// current block into the beginning of DestBlock, which can only happen if it's
12614/// safe to move the instruction past all of the instructions between it and the
12615/// end of its block.
12616static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12617 assert(I->hasOneUse() && "Invariants didn't hold!");
12618
Chris Lattner108e9022005-10-27 17:13:11 +000012619 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012620 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012621 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012622
Chris Lattnerea1c4542004-12-08 23:43:58 +000012623 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012624 if (isa<AllocaInst>(I) && I->getParent() ==
12625 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012626 return false;
12627
Chris Lattner96a52a62004-12-09 07:14:34 +000012628 // We can only sink load instructions if there is nothing between the load and
12629 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012630 if (I->mayReadFromMemory()) {
12631 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012632 Scan != E; ++Scan)
12633 if (Scan->mayWriteToMemory())
12634 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012635 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012636
Dan Gohman02dea8b2008-05-23 21:05:58 +000012637 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012638
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012639 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012640 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012641 ++NumSunkInst;
12642 return true;
12643}
12644
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012645
12646/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12647/// all reachable code to the worklist.
12648///
12649/// This has a couple of tricks to make the code faster and more powerful. In
12650/// particular, we constant fold and DCE instructions as we go, to avoid adding
12651/// them to the worklist (this significantly speeds up instcombine on code where
12652/// many instructions are dead or constant). Additionally, if we find a branch
12653/// whose condition is a known constant, we only visit the reachable successors.
12654///
12655static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012656 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012657 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012658 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012659 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012660 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012661
Chris Lattner2c7718a2007-03-23 19:17:18 +000012662 while (!Worklist.empty()) {
12663 BB = Worklist.back();
12664 Worklist.pop_back();
12665
12666 // We have now visited this block! If we've already been here, ignore it.
12667 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012668
12669 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012670 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12671 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012672
Chris Lattner2c7718a2007-03-23 19:17:18 +000012673 // DCE instruction if trivially dead.
12674 if (isInstructionTriviallyDead(Inst)) {
12675 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012676 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012677 Inst->eraseFromParent();
12678 continue;
12679 }
12680
12681 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012682 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012683 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12684 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012685 Inst->replaceAllUsesWith(C);
12686 ++NumConstProp;
12687 Inst->eraseFromParent();
12688 continue;
12689 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012690
Devang Patel7fe1dec2008-11-19 18:56:50 +000012691 // If there are two consecutive llvm.dbg.stoppoint calls then
12692 // it is likely that the optimizer deleted code in between these
12693 // two intrinsics.
12694 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12695 if (DBI_Next) {
12696 if (DBI_Prev
12697 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12698 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012699 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012700 DBI_Prev->eraseFromParent();
12701 }
12702 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012703 } else {
12704 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012705 }
12706
Chris Lattner7a1e9242009-08-30 06:13:40 +000012707 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012708 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012709
12710 // Recursively visit successors. If this is a branch or switch on a
12711 // constant, only visit the reachable successor.
12712 TerminatorInst *TI = BB->getTerminator();
12713 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12714 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12715 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012716 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012717 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012718 continue;
12719 }
12720 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12721 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12722 // See if this is an explicit destination.
12723 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12724 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012725 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012726 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012727 continue;
12728 }
12729
12730 // Otherwise it is the default destination.
12731 Worklist.push_back(SI->getSuccessor(0));
12732 continue;
12733 }
12734 }
12735
12736 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12737 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012738 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012739}
12740
Chris Lattnerec9c3582007-03-03 02:04:50 +000012741bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012742 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012743 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012744
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012745 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12746 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012747
Chris Lattnerb3d59702005-07-07 20:40:38 +000012748 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012749 // Do a depth-first traversal of the function, populate the worklist with
12750 // the reachable instructions. Ignore blocks that are not reachable. Keep
12751 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012752 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012753 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012754
Chris Lattnerb3d59702005-07-07 20:40:38 +000012755 // Do a quick scan over the function. If we find any blocks that are
12756 // unreachable, remove any instructions inside of them. This prevents
12757 // the instcombine code from having to deal with some bad special cases.
12758 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12759 if (!Visited.count(BB)) {
12760 Instruction *Term = BB->getTerminator();
12761 while (Term != BB->begin()) { // Remove instrs bottom-up
12762 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012763
Chris Lattnerbdff5482009-08-23 04:37:46 +000012764 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012765 // A debug intrinsic shouldn't force another iteration if we weren't
12766 // going to do one without it.
12767 if (!isa<DbgInfoIntrinsic>(I)) {
12768 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012769 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012770 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012771 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012772 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012773 I->eraseFromParent();
12774 }
12775 }
12776 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012777
Chris Lattner873ff012009-08-30 05:55:36 +000012778 while (!Worklist.isEmpty()) {
12779 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012780 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012781
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012782 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012783 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012784 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012785 EraseInstFromFunction(*I);
12786 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012787 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012788 continue;
12789 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012790
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012791 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012792 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012793 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012794
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012795 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012796 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012797 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012798 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012799 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012800 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012801 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012802
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012803 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012804 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012805 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12806 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012807 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12808 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012809 if (NewC != CE) {
12810 i->set(NewC);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012811 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012812 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012813 }
12814
Chris Lattnerea1c4542004-12-08 23:43:58 +000012815 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012816 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012817 BasicBlock *BB = I->getParent();
12818 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12819 if (UserParent != BB) {
12820 bool UserIsSuccessor = false;
12821 // See if the user is one of our successors.
12822 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12823 if (*SI == UserParent) {
12824 UserIsSuccessor = true;
12825 break;
12826 }
12827
12828 // If the user is one of our immediate successors, and if that successor
12829 // only has us as a predecessors (we'd have to split the critical edge
12830 // otherwise), we can keep going.
12831 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12832 next(pred_begin(UserParent)) == pred_end(UserParent))
12833 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012834 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012835 }
12836 }
12837
Chris Lattner74381062009-08-30 07:44:24 +000012838 // Now that we have an instruction, try combining it to simplify it.
12839 Builder->SetInsertPoint(I->getParent(), I);
12840
Reid Spencera9b81012007-03-26 17:44:01 +000012841#ifndef NDEBUG
12842 std::string OrigI;
12843#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012844 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012845
Chris Lattner90ac28c2002-08-02 19:29:35 +000012846 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012847 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012848 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012849 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012850 DEBUG(errs() << "IC: Old = " << *I << '\n'
12851 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012852
Chris Lattnerf523d062004-06-09 05:08:07 +000012853 // Everything uses the new instruction now.
12854 I->replaceAllUsesWith(Result);
12855
12856 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012857 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012858 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012859
Chris Lattner6934a042007-02-11 01:23:03 +000012860 // Move the name to the new instruction first.
12861 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012862
12863 // Insert the new instruction into the basic block...
12864 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012865 BasicBlock::iterator InsertPos = I;
12866
12867 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12868 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12869 ++InsertPos;
12870
12871 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012872
Chris Lattner7a1e9242009-08-30 06:13:40 +000012873 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012874 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012875#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012876 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12877 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012878#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012879
Chris Lattner90ac28c2002-08-02 19:29:35 +000012880 // If the instruction was modified, it's possible that it is now dead.
12881 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012882 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012883 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012884 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012885 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012886 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012887 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012888 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012889 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012890 }
12891 }
12892
Chris Lattner873ff012009-08-30 05:55:36 +000012893 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012894 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012895}
12896
Chris Lattnerec9c3582007-03-03 02:04:50 +000012897
12898bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012899 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012900 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012901
Chris Lattner74381062009-08-30 07:44:24 +000012902
12903 /// Builder - This is an IRBuilder that automatically inserts new
12904 /// instructions into the worklist when they are created.
12905 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12906 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12907 InstCombineIRInserter(Worklist));
12908 Builder = &TheBuilder;
12909
Chris Lattnerec9c3582007-03-03 02:04:50 +000012910 bool EverMadeChange = false;
12911
12912 // Iterate while there is work to do.
12913 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012914 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012915 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012916
12917 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012918 return EverMadeChange;
12919}
12920
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012921FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012922 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012923}