blob: dcb65a8ed91dd34d7d6b2e0a12bcbfd091ac8bcc [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) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000093 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
94 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000095 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000096 }
Chris Lattner873ff012009-08-30 05:55:36 +000097 }
98
Chris Lattner3c4e38e2009-08-30 06:27:41 +000099 void AddValue(Value *V) {
100 if (Instruction *I = dyn_cast<Instruction>(V))
101 Add(I);
102 }
103
Chris Lattner7a1e9242009-08-30 06:13:40 +0000104 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000105 void Remove(Instruction *I) {
106 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
107 if (It == WorklistMap.end()) return; // Not in worklist.
108
109 // Don't bother moving everything down, just null out the slot.
110 Worklist[It->second] = 0;
111
112 WorklistMap.erase(It);
113 }
114
115 Instruction *RemoveOne() {
116 Instruction *I = Worklist.back();
117 Worklist.pop_back();
118 WorklistMap.erase(I);
119 return I;
120 }
121
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000122 /// AddUsersToWorkList - When an instruction is simplified, add all users of
123 /// the instruction to the work lists because they might get more simplified
124 /// now.
125 ///
126 void AddUsersToWorkList(Instruction &I) {
127 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
128 UI != UE; ++UI)
129 Add(cast<Instruction>(*UI));
130 }
131
Chris Lattner873ff012009-08-30 05:55:36 +0000132
133 /// Zap - check that the worklist is empty and nuke the backing store for
134 /// the map if it is large.
135 void Zap() {
136 assert(WorklistMap.empty() && "Worklist empty, but map not?");
137
138 // Do an explicit clear, this shrinks the map if needed.
139 WorklistMap.clear();
140 }
141 };
142} // end anonymous namespace.
143
144
145namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000146 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
147 /// just like the normal insertion helper, but also adds any new instructions
148 /// to the instcombine worklist.
149 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
150 InstCombineWorklist &Worklist;
151 public:
152 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
153
154 void InsertHelper(Instruction *I, const Twine &Name,
155 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
156 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
157 Worklist.Add(I);
158 }
159 };
160} // end anonymous namespace
161
162
163namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000164 class InstCombiner : public FunctionPass,
165 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000166 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000167 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000168 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000169 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000170 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000171 InstCombineWorklist Worklist;
172
Chris Lattner74381062009-08-30 07:44:24 +0000173 /// Builder - This is an IRBuilder that automatically inserts new
174 /// instructions into the worklist when they are created.
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000175 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
176 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000177
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000178 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000179 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000180
Owen Andersone922c022009-07-22 00:24:57 +0000181 LLVMContext *Context;
182 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000183
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000184 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000185 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000186
187 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000188
Chris Lattner97e52e42002-04-28 21:27:06 +0000189 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000190 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000191 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000192 }
193
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000194 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000195
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000196 // Visitation implementation - Implement instruction combining for different
197 // instruction types. The semantics are as follows:
198 // Return Value:
199 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000200 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000201 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000202 //
Chris Lattner7e708292002-06-25 16:13:24 +0000203 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000204 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000205 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000207 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000208 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000209 Instruction *visitURem(BinaryOperator &I);
210 Instruction *visitSRem(BinaryOperator &I);
211 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000212 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000213 Instruction *commonRemTransforms(BinaryOperator &I);
214 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000215 Instruction *commonDivTransforms(BinaryOperator &I);
216 Instruction *commonIDivTransforms(BinaryOperator &I);
217 Instruction *visitUDiv(BinaryOperator &I);
218 Instruction *visitSDiv(BinaryOperator &I);
219 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000220 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000221 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000223 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000224 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000225 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000226 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000227 Instruction *visitOr (BinaryOperator &I);
228 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000229 Instruction *visitShl(BinaryOperator &I);
230 Instruction *visitAShr(BinaryOperator &I);
231 Instruction *visitLShr(BinaryOperator &I);
232 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000233 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
234 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000235 Instruction *visitFCmpInst(FCmpInst &I);
236 Instruction *visitICmpInst(ICmpInst &I);
237 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000238 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
239 Instruction *LHS,
240 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000241 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
242 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000243
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000244 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000245 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000246 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000247 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000248 Instruction *commonCastTransforms(CastInst &CI);
249 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000250 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000251 Instruction *visitTrunc(TruncInst &CI);
252 Instruction *visitZExt(ZExtInst &CI);
253 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000254 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000255 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000256 Instruction *visitFPToUI(FPToUIInst &FI);
257 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000258 Instruction *visitUIToFP(CastInst &CI);
259 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000260 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000261 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000262 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000263 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
264 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000265 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000266 Instruction *visitSelectInst(SelectInst &SI);
267 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000268 Instruction *visitCallInst(CallInst &CI);
269 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000270 Instruction *visitPHINode(PHINode &PN);
271 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000272 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000273 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000274 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000275 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000276 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000277 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000278 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000279 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000280 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000281 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000282
283 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000284 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000285
Chris Lattner9fe38862003-06-19 17:00:31 +0000286 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000287 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000288 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000289 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000290 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
291 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000292 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000293 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
294
Chris Lattner9fe38862003-06-19 17:00:31 +0000295
Chris Lattner28977af2004-04-05 01:30:19 +0000296 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000297 // InsertNewInstBefore - insert an instruction New before instruction Old
298 // in the program. Add the new instruction to the worklist.
299 //
Chris Lattner955f3312004-09-28 21:48:02 +0000300 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000301 assert(New && New->getParent() == 0 &&
302 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000303 BasicBlock *BB = Old.getParent();
304 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000305 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000306 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000307 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000308
Chris Lattner8b170942002-08-09 23:47:40 +0000309 // ReplaceInstUsesWith - This method is to be used when an instruction is
310 // found to be dead, replacable with another preexisting expression. Here
311 // we add all uses of I to the worklist, replace all uses of I with the new
312 // value, then return I, so that the inst combiner will know that I was
313 // modified.
314 //
315 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000316 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000317
318 // If we are replacing the instruction with itself, this must be in a
319 // segment of unreachable code, so just clobber the instruction.
320 if (&I == V)
321 V = UndefValue::get(I.getType());
322
323 I.replaceAllUsesWith(V);
324 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000325 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000326
327 // EraseInstFromFunction - When dealing with an instruction that has side
328 // effects or produces a void value, we can't rely on DCE to delete the
329 // instruction. Instead, visit methods should return the value returned by
330 // this function.
331 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000332 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000333
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000334 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000335 // Make sure that we reprocess all operands now that we reduced their
336 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000337 if (I.getNumOperands() < 8) {
338 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
339 if (Instruction *Op = dyn_cast<Instruction>(*i))
340 Worklist.Add(Op);
341 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000342 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000343 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000344 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000345 return 0; // Don't do anything with FI
346 }
Chris Lattner173234a2008-06-02 01:18:21 +0000347
348 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
349 APInt &KnownOne, unsigned Depth = 0) const {
350 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
351 }
352
353 bool MaskedValueIsZero(Value *V, const APInt &Mask,
354 unsigned Depth = 0) const {
355 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
356 }
357 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
358 return llvm::ComputeNumSignBits(Op, TD, Depth);
359 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000360
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000361 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000362
Reid Spencere4d87aa2006-12-23 06:05:41 +0000363 /// SimplifyCommutative - This performs a few simplifications for
364 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000365 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000366
Reid Spencere4d87aa2006-12-23 06:05:41 +0000367 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
368 /// most-complex to least-complex order.
369 bool SimplifyCompare(CmpInst &I);
370
Chris Lattner886ab6c2009-01-31 08:15:18 +0000371 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
372 /// based on the demanded bits.
373 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
374 APInt& KnownZero, APInt& KnownOne,
375 unsigned Depth);
376 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000377 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000378 unsigned Depth=0);
379
380 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
381 /// SimplifyDemandedBits knows about. See if the instruction has any
382 /// properties that allow us to simplify its operands.
383 bool SimplifyDemandedInstructionBits(Instruction &Inst);
384
Evan Cheng388df622009-02-03 10:05:09 +0000385 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
386 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000387
Chris Lattner5d1704d2009-09-27 19:57:57 +0000388 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
389 // which has a PHI node as operand #0, see if we can fold the instruction
390 // into the PHI (which is only possible if all operands to the PHI are
391 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000392 //
393 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
394 // that would normally be unprofitable because they strongly encourage jump
395 // threading.
396 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000397
Chris Lattnerbac32862004-11-14 19:13:23 +0000398 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
399 // operator and they all are only used by the PHI, PHI together their
400 // inputs, and do the operation once, to the result of the PHI.
401 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000402 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000403 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
404
Chris Lattner7da52b22006-11-01 04:51:18 +0000405
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000406 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
407 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000408
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000409 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000410 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000411 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000412 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000413 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000414 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000415 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000416 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000417 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000418
Chris Lattnerafe91a52006-06-15 19:07:26 +0000419
Reid Spencerc55b2432006-12-13 18:21:21 +0000420 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000421
Dan Gohman6de29f82009-06-15 22:12:54 +0000422 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000423 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000424 unsigned GetOrEnforceKnownAlignment(Value *V,
425 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000426
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000427 };
Chris Lattner873ff012009-08-30 05:55:36 +0000428} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000429
Dan Gohman844731a2008-05-13 00:00:25 +0000430char InstCombiner::ID = 0;
431static RegisterPass<InstCombiner>
432X("instcombine", "Combine redundant instructions");
433
Chris Lattner4f98c562003-03-10 21:43:22 +0000434// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000435// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000436static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000437 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000438 if (BinaryOperator::isNeg(V) ||
439 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000440 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000441 return 3;
442 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000443 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000444 if (isa<Argument>(V)) return 3;
445 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000446}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000447
Chris Lattnerc8802d22003-03-11 00:12:48 +0000448// isOnlyUse - Return true if this instruction will be deleted if we stop using
449// it.
450static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000451 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000452}
453
Chris Lattner4cb170c2004-02-23 06:38:22 +0000454// getPromotedType - Return the specified type promoted as it would be to pass
455// though a va_arg area...
456static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000457 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
458 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000459 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000460 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000461 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000462}
463
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000464/// getBitCastOperand - If the specified operand is a CastInst, a constant
465/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
466/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000467static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000468 if (Operator *O = dyn_cast<Operator>(V)) {
469 if (O->getOpcode() == Instruction::BitCast)
470 return O->getOperand(0);
471 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
472 if (GEP->hasAllZeroIndices())
473 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000474 }
Chris Lattnereed48272005-09-13 00:40:14 +0000475 return 0;
476}
477
Reid Spencer3da59db2006-11-27 01:05:10 +0000478/// This function is a wrapper around CastInst::isEliminableCastPair. It
479/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000480static Instruction::CastOps
481isEliminableCastPair(
482 const CastInst *CI, ///< The first cast instruction
483 unsigned opcode, ///< The opcode of the second cast instruction
484 const Type *DstTy, ///< The target type for the second cast instruction
485 TargetData *TD ///< The target data for pointer size
486) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000487
Reid Spencer3da59db2006-11-27 01:05:10 +0000488 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
489 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000490
Reid Spencer3da59db2006-11-27 01:05:10 +0000491 // Get the opcodes of the two Cast instructions
492 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
493 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000494
Chris Lattnera0e69692009-03-24 18:35:40 +0000495 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000496 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000497 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000498
499 // We don't want to form an inttoptr or ptrtoint that converts to an integer
500 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000501 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000502 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000503 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000504 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000505 Res = 0;
506
507 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000508}
509
510/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
511/// in any code being generated. It does not require codegen if V is simple
512/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000513static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
514 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000515 if (V->getType() == Ty || isa<Constant>(V)) return false;
516
Chris Lattner01575b72006-05-25 23:24:33 +0000517 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000518 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000519 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000520 return false;
521 return true;
522}
523
Chris Lattner4f98c562003-03-10 21:43:22 +0000524// SimplifyCommutative - This performs a few simplifications for commutative
525// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000526//
Chris Lattner4f98c562003-03-10 21:43:22 +0000527// 1. Order operands such that they are listed from right (least complex) to
528// left (most complex). This puts constants before unary operators before
529// binary operators.
530//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
532// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000533//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000535 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000536 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000537 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000538
Chris Lattner4f98c562003-03-10 21:43:22 +0000539 if (!I.isAssociative()) return Changed;
540 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
542 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
543 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000544 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000545 cast<Constant>(I.getOperand(1)),
546 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547 I.setOperand(0, Op->getOperand(0));
548 I.setOperand(1, Folded);
549 return true;
550 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
551 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
552 isOnlyUse(Op) && isOnlyUse(Op1)) {
553 Constant *C1 = cast<Constant>(Op->getOperand(1));
554 Constant *C2 = cast<Constant>(Op1->getOperand(1));
555
556 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000557 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000558 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000559 Op1->getOperand(0),
560 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000561 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000562 I.setOperand(0, New);
563 I.setOperand(1, Folded);
564 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000565 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000566 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000567 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000568}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000569
Reid Spencere4d87aa2006-12-23 06:05:41 +0000570/// SimplifyCompare - For a CmpInst this function just orders the operands
571/// so that theyare listed from right (least complex) to left (most complex).
572/// This puts constants before unary operators before binary operators.
573bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000574 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000575 return false;
576 I.swapOperands();
577 // Compare instructions are not associative so there's nothing else we can do.
578 return true;
579}
580
Chris Lattner8d969642003-03-10 23:06:50 +0000581// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
582// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000583//
Dan Gohman186a6362009-08-12 16:04:34 +0000584static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000585 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000586 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000587
Chris Lattner0ce85802004-12-14 20:08:06 +0000588 // Constants can be considered to be negated values if they can be folded.
589 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000590 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000591
592 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
593 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000594 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000595
Chris Lattner8d969642003-03-10 23:06:50 +0000596 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000597}
598
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000599// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
600// instruction if the LHS is a constant negative zero (which is the 'negate'
601// form).
602//
Dan Gohman186a6362009-08-12 16:04:34 +0000603static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000604 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000605 return BinaryOperator::getFNegArgument(V);
606
607 // Constants can be considered to be negated values if they can be folded.
608 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000609 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000610
611 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
612 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000613 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000614
615 return 0;
616}
617
Dan Gohman186a6362009-08-12 16:04:34 +0000618static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000619 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000620 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000621
622 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000623 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000624 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000625 return 0;
626}
627
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628// dyn_castFoldableMul - If this value is a multiply that can be folded into
629// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000630// non-constant operand of the multiply, and set CST to point to the multiplier.
631// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000632//
Dan Gohman186a6362009-08-12 16:04:34 +0000633static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000634 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000635 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000636 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000637 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000638 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000639 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000640 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000641 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000642 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000643 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000644 CST = ConstantInt::get(V->getType()->getContext(),
645 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000646 return I->getOperand(0);
647 }
648 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000649 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000650}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000651
Reid Spencer7177c3a2007-03-25 05:33:51 +0000652/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000653static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000654 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000655 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000656}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000657/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000658static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000659 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000660 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000661}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000662/// MultiplyOverflows - True if the multiply can not be expressed in an int
663/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000664static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000665 uint32_t W = C1->getBitWidth();
666 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
667 if (sign) {
668 LHSExt.sext(W * 2);
669 RHSExt.sext(W * 2);
670 } else {
671 LHSExt.zext(W * 2);
672 RHSExt.zext(W * 2);
673 }
674
675 APInt MulExt = LHSExt * RHSExt;
676
677 if (sign) {
678 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
679 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
680 return MulExt.slt(Min) || MulExt.sgt(Max);
681 } else
682 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
683}
Chris Lattner955f3312004-09-28 21:48:02 +0000684
Reid Spencere7816b52007-03-08 01:52:58 +0000685
Chris Lattner255d8912006-02-11 09:31:47 +0000686/// ShrinkDemandedConstant - Check to see if the specified operand of the
687/// specified instruction is a constant integer. If so, check to see if there
688/// are any bits set in the constant that are not demanded. If so, shrink the
689/// constant and return true.
690static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000691 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000692 assert(I && "No instruction?");
693 assert(OpNo < I->getNumOperands() && "Operand index too large");
694
695 // If the operand is not a constant integer, nothing to do.
696 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
697 if (!OpC) return false;
698
699 // If there are no bits set that aren't demanded, nothing to do.
700 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
701 if ((~Demanded & OpC->getValue()) == 0)
702 return false;
703
704 // This instruction is producing bits that are not demanded. Shrink the RHS.
705 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000706 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000707 return true;
708}
709
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000710// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
711// set of known zero and one bits, compute the maximum and minimum values that
712// could have the specified known zero and known one bits, returning them in
713// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000714static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000715 const APInt& KnownOne,
716 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000717 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
718 KnownZero.getBitWidth() == Min.getBitWidth() &&
719 KnownZero.getBitWidth() == Max.getBitWidth() &&
720 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000721 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000723 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
724 // bit if it is unknown.
725 Min = KnownOne;
726 Max = KnownOne|UnknownBits;
727
Dan Gohman1c8491e2009-04-25 17:12:48 +0000728 if (UnknownBits.isNegative()) { // Sign bit is unknown
729 Min.set(Min.getBitWidth()-1);
730 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000731 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000732}
733
734// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
735// a set of known zero and one bits, compute the maximum and minimum values that
736// could have the specified known zero and known one bits, returning them in
737// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000738static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000739 const APInt &KnownOne,
740 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000741 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
742 KnownZero.getBitWidth() == Min.getBitWidth() &&
743 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000744 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000745 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000746
747 // The minimum value is when the unknown bits are all zeros.
748 Min = KnownOne;
749 // The maximum value is when the unknown bits are all ones.
750 Max = KnownOne|UnknownBits;
751}
Chris Lattner255d8912006-02-11 09:31:47 +0000752
Chris Lattner886ab6c2009-01-31 08:15:18 +0000753/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
754/// SimplifyDemandedBits knows about. See if the instruction has any
755/// properties that allow us to simplify its operands.
756bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000757 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000758 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
759 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
760
761 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
762 KnownZero, KnownOne, 0);
763 if (V == 0) return false;
764 if (V == &Inst) return true;
765 ReplaceInstUsesWith(Inst, V);
766 return true;
767}
768
769/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
770/// specified instruction operand if possible, updating it in place. It returns
771/// true if it made any change and false otherwise.
772bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
773 APInt &KnownZero, APInt &KnownOne,
774 unsigned Depth) {
775 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
776 KnownZero, KnownOne, Depth);
777 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000778 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000779 return true;
780}
781
782
783/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
784/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000785/// that only the bits set in DemandedMask of the result of V are ever used
786/// downstream. Consequently, depending on the mask and V, it may be possible
787/// to replace V with a constant or one of its operands. In such cases, this
788/// function does the replacement and returns true. In all other cases, it
789/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000790/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000791/// to be zero in the expression. These are provided to potentially allow the
792/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
793/// the expression. KnownOne and KnownZero always follow the invariant that
794/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
795/// the bits in KnownOne and KnownZero may only be accurate for those bits set
796/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
797/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000798///
799/// This returns null if it did not change anything and it permits no
800/// simplification. This returns V itself if it did some simplification of V's
801/// operands based on the information about what bits are demanded. This returns
802/// some other non-null value if it found out that V is equal to another value
803/// in the context where the specified bits are demanded, but not for all users.
804Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
805 APInt &KnownZero, APInt &KnownOne,
806 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000807 assert(V != 0 && "Null pointer of Value???");
808 assert(Depth <= 6 && "Limit Search Depth");
809 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000810 const Type *VTy = V->getType();
811 assert((TD || !isa<PointerType>(VTy)) &&
812 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000813 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
814 (!VTy->isIntOrIntVector() ||
815 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000816 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000817 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000818 "Value *V, DemandedMask, KnownZero and KnownOne "
819 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
821 // We know all of the bits for a constant!
822 KnownOne = CI->getValue() & DemandedMask;
823 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000824 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000826 if (isa<ConstantPointerNull>(V)) {
827 // We know all of the bits for a constant!
828 KnownOne.clear();
829 KnownZero = DemandedMask;
830 return 0;
831 }
832
Chris Lattner08d2cc72009-01-31 07:26:06 +0000833 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000834 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000835 if (DemandedMask == 0) { // Not demanding any bits from V.
836 if (isa<UndefValue>(V))
837 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000838 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000839 }
840
Chris Lattner4598c942009-01-31 08:24:16 +0000841 if (Depth == 6) // Limit search depth.
842 return 0;
843
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000844 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
845 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
846
Dan Gohman1c8491e2009-04-25 17:12:48 +0000847 Instruction *I = dyn_cast<Instruction>(V);
848 if (!I) {
849 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
850 return 0; // Only analyze instructions.
851 }
852
Chris Lattner4598c942009-01-31 08:24:16 +0000853 // If there are multiple uses of this value and we aren't at the root, then
854 // we can't do any simplifications of the operands, because DemandedMask
855 // only reflects the bits demanded by *one* of the users.
856 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000857 // Despite the fact that we can't simplify this instruction in all User's
858 // context, we can at least compute the knownzero/knownone bits, and we can
859 // do simplifications that apply to *just* the one user if we know that
860 // this instruction has a simpler value in that context.
861 if (I->getOpcode() == Instruction::And) {
862 // If either the LHS or the RHS are Zero, the result is zero.
863 ComputeMaskedBits(I->getOperand(1), DemandedMask,
864 RHSKnownZero, RHSKnownOne, Depth+1);
865 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
866 LHSKnownZero, LHSKnownOne, Depth+1);
867
868 // If all of the demanded bits are known 1 on one side, return the other.
869 // These bits cannot contribute to the result of the 'and' in this
870 // context.
871 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
872 (DemandedMask & ~LHSKnownZero))
873 return I->getOperand(0);
874 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
875 (DemandedMask & ~RHSKnownZero))
876 return I->getOperand(1);
877
878 // If all of the demanded bits in the inputs are known zeros, return zero.
879 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000880 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000881
882 } else if (I->getOpcode() == Instruction::Or) {
883 // We can simplify (X|Y) -> X or Y in the user's context if we know that
884 // only bits from X or Y are demanded.
885
886 // If either the LHS or the RHS are One, the result is One.
887 ComputeMaskedBits(I->getOperand(1), DemandedMask,
888 RHSKnownZero, RHSKnownOne, Depth+1);
889 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
890 LHSKnownZero, LHSKnownOne, Depth+1);
891
892 // If all of the demanded bits are known zero on one side, return the
893 // other. These bits cannot contribute to the result of the 'or' in this
894 // context.
895 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
896 (DemandedMask & ~LHSKnownOne))
897 return I->getOperand(0);
898 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
899 (DemandedMask & ~RHSKnownOne))
900 return I->getOperand(1);
901
902 // If all of the potentially set bits on one side are known to be set on
903 // the other side, just use the 'other' side.
904 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
905 (DemandedMask & (~RHSKnownZero)))
906 return I->getOperand(0);
907 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
908 (DemandedMask & (~LHSKnownZero)))
909 return I->getOperand(1);
910 }
911
Chris Lattner4598c942009-01-31 08:24:16 +0000912 // Compute the KnownZero/KnownOne bits to simplify things downstream.
913 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
914 return 0;
915 }
916
917 // If this is the root being simplified, allow it to have multiple uses,
918 // just set the DemandedMask to all bits so that we can try to simplify the
919 // operands. This allows visitTruncInst (for example) to simplify the
920 // operand of a trunc without duplicating all the logic below.
921 if (Depth == 0 && !V->hasOneUse())
922 DemandedMask = APInt::getAllOnesValue(BitWidth);
923
Reid Spencer8cb68342007-03-12 17:25:59 +0000924 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000925 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000926 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000927 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000928 case Instruction::And:
929 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000930 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
931 RHSKnownZero, RHSKnownOne, Depth+1) ||
932 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000933 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000934 return I;
935 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
936 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000937
938 // If all of the demanded bits are known 1 on one side, return the other.
939 // These bits cannot contribute to the result of the 'and'.
940 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
941 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000942 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000943 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
944 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000945 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000946
947 // If all of the demanded bits in the inputs are known zeros, return zero.
948 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000949 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000950
951 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000952 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000953 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000954
955 // Output known-1 bits are only known if set in both the LHS & RHS.
956 RHSKnownOne &= LHSKnownOne;
957 // Output known-0 are known to be clear if zero in either the LHS | RHS.
958 RHSKnownZero |= LHSKnownZero;
959 break;
960 case Instruction::Or:
961 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
963 RHSKnownZero, RHSKnownOne, Depth+1) ||
964 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000965 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000966 return I;
967 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
968 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000969
970 // If all of the demanded bits are known zero on one side, return the other.
971 // These bits cannot contribute to the result of the 'or'.
972 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
973 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000975 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
976 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000977 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000978
979 // If all of the potentially set bits on one side are known to be set on
980 // the other side, just use the 'other' side.
981 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
982 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000984 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
985 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987
988 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000989 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // Output known-0 bits are only known if clear in both the LHS & RHS.
993 RHSKnownZero &= LHSKnownZero;
994 // Output known-1 are known to be set if set in either the LHS | RHS.
995 RHSKnownOne |= LHSKnownOne;
996 break;
997 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000998 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1) ||
1000 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001001 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001002 return I;
1003 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1004 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001005
1006 // If all of the demanded bits are known zero on one side, return the other.
1007 // These bits cannot contribute to the result of the 'xor'.
1008 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001009 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001010 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001012
1013 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1014 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1015 (RHSKnownOne & LHSKnownOne);
1016 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1017 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1018 (RHSKnownOne & LHSKnownZero);
1019
1020 // If all of the demanded bits are known to be zero on one side or the
1021 // other, turn this into an *inclusive* or.
1022 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001023 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1024 Instruction *Or =
1025 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1026 I->getName());
1027 return InsertNewInstBefore(Or, *I);
1028 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001029
1030 // If all of the demanded bits on one side are known, and all of the set
1031 // bits on that side are also known to be set on the other side, turn this
1032 // into an AND, as we know the bits will be cleared.
1033 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1034 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1035 // all known
1036 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001037 Constant *AndC = Constant::getIntegerValue(VTy,
1038 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001039 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001040 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001042 }
1043 }
1044
1045 // If the RHS is a constant, see if we can simplify it.
1046 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001047 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001048 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001049
Chris Lattnerd0883142009-10-11 22:22:13 +00001050 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1051 // are flipping are known to be set, then the xor is just resetting those
1052 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1053 // simplifying both of them.
1054 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1055 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1056 isa<ConstantInt>(I->getOperand(1)) &&
1057 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1058 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1059 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1060 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1061 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1062
1063 Constant *AndC =
1064 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1065 Instruction *NewAnd =
1066 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1067 InsertNewInstBefore(NewAnd, *I);
1068
1069 Constant *XorC =
1070 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1071 Instruction *NewXor =
1072 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1073 return InsertNewInstBefore(NewXor, *I);
1074 }
1075
1076
Reid Spencer8cb68342007-03-12 17:25:59 +00001077 RHSKnownZero = KnownZeroOut;
1078 RHSKnownOne = KnownOneOut;
1079 break;
1080 }
1081 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1083 RHSKnownZero, RHSKnownOne, Depth+1) ||
1084 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001085 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001086 return I;
1087 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1088 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001089
1090 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001091 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1092 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001093 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001094
1095 // Only known if known in both the LHS and RHS.
1096 RHSKnownOne &= LHSKnownOne;
1097 RHSKnownZero &= LHSKnownZero;
1098 break;
1099 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001100 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001101 DemandedMask.zext(truncBf);
1102 RHSKnownZero.zext(truncBf);
1103 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001104 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001105 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 DemandedMask.trunc(BitWidth);
1108 RHSKnownZero.trunc(BitWidth);
1109 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001111 break;
1112 }
1113 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001114 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001116
1117 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1118 if (const VectorType *SrcVTy =
1119 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1120 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1121 // Don't touch a bitcast between vectors of different element counts.
1122 return false;
1123 } else
1124 // Don't touch a scalar-to-vector bitcast.
1125 return false;
1126 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1127 // Don't touch a vector-to-scalar bitcast.
1128 return false;
1129
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001132 return I;
1133 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001134 break;
1135 case Instruction::ZExt: {
1136 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001137 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001138
Zhou Shengd48653a2007-03-29 04:45:55 +00001139 DemandedMask.trunc(SrcBitWidth);
1140 RHSKnownZero.trunc(SrcBitWidth);
1141 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 DemandedMask.zext(BitWidth);
1146 RHSKnownZero.zext(BitWidth);
1147 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001150 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 break;
1152 }
1153 case Instruction::SExt: {
1154 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001155 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001156
Reid Spencer8cb68342007-03-12 17:25:59 +00001157 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001158 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001159
Zhou Sheng01542f32007-03-29 02:26:30 +00001160 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 // If any of the sign extended bits are demanded, we know that the sign
1162 // bit is demanded.
1163 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001164 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001165
Zhou Shengd48653a2007-03-29 04:45:55 +00001166 InputDemandedBits.trunc(SrcBitWidth);
1167 RHSKnownZero.trunc(SrcBitWidth);
1168 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001170 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001171 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 InputDemandedBits.zext(BitWidth);
1173 RHSKnownZero.zext(BitWidth);
1174 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001175 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // If the sign bit of the input is known set or clear, then we know the
1178 // top bits of the result.
1179
1180 // If the input sign bit is known zero, or if the NewBits are not demanded
1181 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001182 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001183 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1185 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001186 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 }
1189 break;
1190 }
1191 case Instruction::Add: {
1192 // Figure out what the input bits are. If the top bits of the and result
1193 // are not demanded, then the add doesn't demand them from its input
1194 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001195 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001196
1197 // If there is a constant on the RHS, there are a variety of xformations
1198 // we can do.
1199 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1200 // If null, this should be simplified elsewhere. Some of the xforms here
1201 // won't work if the RHS is zero.
1202 if (RHS->isZero())
1203 break;
1204
1205 // If the top bit of the output is demanded, demand everything from the
1206 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001207 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001208
1209 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001210 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001211 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001213
1214 // If the RHS of the add has bits set that can't affect the input, reduce
1215 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001216 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218
1219 // Avoid excess work.
1220 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1221 break;
1222
1223 // Turn it into OR if input bits are zero.
1224 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1225 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001226 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 }
1230
1231 // We can say something about the output known-zero and known-one bits,
1232 // depending on potential carries from the input constant and the
1233 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1234 // bits set and the RHS constant is 0x01001, then we know we have a known
1235 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1236
1237 // To compute this, we first compute the potential carry bits. These are
1238 // the bits which may be modified. I'm not aware of a better way to do
1239 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001241 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001242
1243 // Now that we know which bits have carries, compute the known-1/0 sets.
1244
1245 // Bits are known one if they are known zero in one operand and one in the
1246 // other, and there is no input carry.
1247 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1248 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1249
1250 // Bits are known zero if they are known zero in both operands and there
1251 // is no input carry.
1252 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1253 } else {
1254 // If the high-bits of this ADD are not demanded, then it does not demand
1255 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001256 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001257 // Right fill the mask of bits for this ADD to demand the most
1258 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001259 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001260 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1261 LHSKnownZero, LHSKnownOne, Depth+1) ||
1262 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001263 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 }
1266 }
1267 break;
1268 }
1269 case Instruction::Sub:
1270 // If the high-bits of this SUB are not demanded, then it does not demand
1271 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001272 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 // Right fill the mask of bits for this SUB to demand the most
1274 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001275 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001276 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001277 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1278 LHSKnownZero, LHSKnownOne, Depth+1) ||
1279 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001281 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001283 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1284 // the known zeros and ones.
1285 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 break;
1287 case Instruction::Shl:
1288 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001289 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001290 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001293 return I;
1294 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 RHSKnownZero <<= ShiftAmt;
1296 RHSKnownOne <<= ShiftAmt;
1297 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001298 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001299 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 }
1301 break;
1302 case Instruction::LShr:
1303 // For a logical shift right
1304 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001305 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001308 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 return I;
1312 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1314 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001315 if (ShiftAmt) {
1316 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001317 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001318 RHSKnownZero |= HighBits; // high bits known zero.
1319 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 }
1321 break;
1322 case Instruction::AShr:
1323 // If this is an arithmetic shift right and only the low-bit is set, we can
1324 // always convert this into a logical shr, even if the shift amount is
1325 // variable. The low bit of the shift cannot be an input sign bit unless
1326 // the shift amount is >= the size of the datatype, which is undefined.
1327 if (DemandedMask == 1) {
1328 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001331 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001333
1334 // If the sign bit is the only bit demanded by this ashr, then there is no
1335 // need to do it, the shift doesn't change the high bit.
1336 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001338
1339 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001340 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001341
Reid Spencer8cb68342007-03-12 17:25:59 +00001342 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001343 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001344 // If any of the "high bits" are demanded, we should set the sign bit as
1345 // demanded.
1346 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1347 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001348 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001349 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001350 return I;
1351 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001352 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001353 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001354 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1356
1357 // Handle the sign bits.
1358 APInt SignBit(APInt::getSignBit(BitWidth));
1359 // Adjust to where it is now in the mask.
1360 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1361
1362 // If the input sign bit is known to be zero, or if none of the top bits
1363 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001364 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001365 (HighBits & ~DemandedMask) == HighBits) {
1366 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001369 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001370 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1371 RHSKnownOne |= HighBits;
1372 }
1373 }
1374 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001375 case Instruction::SRem:
1376 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001377 APInt RA = Rem->getValue().abs();
1378 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001379 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001380 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001381
Nick Lewycky8e394322008-11-02 02:41:50 +00001382 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001383 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001384 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001385 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001386 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001387
1388 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1389 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001390
1391 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001392
Chris Lattner886ab6c2009-01-31 08:15:18 +00001393 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001394 }
1395 }
1396 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001397 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001398 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1399 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001400 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1401 KnownZero2, KnownOne2, Depth+1) ||
1402 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001403 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001404 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001405
Chris Lattner455e9ab2009-01-21 18:09:24 +00001406 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001407 Leaders = std::max(Leaders,
1408 KnownZero2.countLeadingOnes());
1409 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001410 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001411 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001412 case Instruction::Call:
1413 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1414 switch (II->getIntrinsicID()) {
1415 default: break;
1416 case Intrinsic::bswap: {
1417 // If the only bits demanded come from one byte of the bswap result,
1418 // just shift the input byte into position to eliminate the bswap.
1419 unsigned NLZ = DemandedMask.countLeadingZeros();
1420 unsigned NTZ = DemandedMask.countTrailingZeros();
1421
1422 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1423 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1424 // have 14 leading zeros, round to 8.
1425 NLZ &= ~7;
1426 NTZ &= ~7;
1427 // If we need exactly one byte, we can do this transformation.
1428 if (BitWidth-NLZ-NTZ == 8) {
1429 unsigned ResultBit = NTZ;
1430 unsigned InputBit = BitWidth-NTZ-8;
1431
1432 // Replace this with either a left or right shift to get the byte into
1433 // the right place.
1434 Instruction *NewVal;
1435 if (InputBit > ResultBit)
1436 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001437 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001438 else
1439 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001440 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001441 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001442 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001443 }
1444
1445 // TODO: Could compute known zero/one bits based on the input.
1446 break;
1447 }
1448 }
1449 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001450 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001451 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001452 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001453
1454 // If the client is only demanding bits that we know, return the known
1455 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001456 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1457 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001458 return false;
1459}
1460
Chris Lattner867b99f2006-10-05 06:55:50 +00001461
Mon P Wangaeb06d22008-11-10 04:46:22 +00001462/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001463/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001464/// actually used by the caller. This method analyzes which elements of the
1465/// operand are undef and returns that information in UndefElts.
1466///
1467/// If the information about demanded elements can be used to simplify the
1468/// operation, the operation is simplified, then the resultant value is
1469/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001470Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1471 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001473 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001474 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001475 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001476
1477 if (isa<UndefValue>(V)) {
1478 // If the entire vector is undefined, just return this info.
1479 UndefElts = EltMask;
1480 return 0;
1481 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1482 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001483 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001485
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001487 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1488 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001489 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001490
1491 std::vector<Constant*> Elts;
1492 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001493 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001494 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001495 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001496 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1497 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001498 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001499 } else { // Otherwise, defined.
1500 Elts.push_back(CP->getOperand(i));
1501 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001502
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001504 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001505 return NewCP != CP ? NewCP : 0;
1506 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001507 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001508 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001509
1510 // Check if this is identity. If so, return 0 since we are not simplifying
1511 // anything.
1512 if (DemandedElts == ((1ULL << VWidth) -1))
1513 return 0;
1514
Reid Spencer9d6565a2007-02-15 02:26:10 +00001515 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001516 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001517 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001519 for (unsigned i = 0; i != VWidth; ++i) {
1520 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1521 Elts.push_back(Elt);
1522 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001524 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 }
1526
Dan Gohman488fbfc2008-09-09 18:11:14 +00001527 // Limit search depth.
1528 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001529 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001530
1531 // If multiple users are using the root value, procede with
1532 // simplification conservatively assuming that all elements
1533 // are needed.
1534 if (!V->hasOneUse()) {
1535 // Quit if we find multiple users of a non-root value though.
1536 // They'll be handled when it's their turn to be visited by
1537 // the main instcombine process.
1538 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001539 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001540 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001541
1542 // Conservatively assume that all elements are needed.
1543 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001544 }
1545
1546 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001547 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001548
1549 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001550 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001551 Value *TmpV;
1552 switch (I->getOpcode()) {
1553 default: break;
1554
1555 case Instruction::InsertElement: {
1556 // If this is a variable index, we don't know which element it overwrites.
1557 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001558 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001559 if (Idx == 0) {
1560 // Note that we can't propagate undef elt info, because we don't know
1561 // which elt is getting updated.
1562 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1563 UndefElts2, Depth+1);
1564 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1565 break;
1566 }
1567
1568 // If this is inserting an element that isn't demanded, remove this
1569 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001570 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001571 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1572 Worklist.Add(I);
1573 return I->getOperand(0);
1574 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001575
1576 // Otherwise, the element inserted overwrites whatever was there, so the
1577 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001578 APInt DemandedElts2 = DemandedElts;
1579 DemandedElts2.clear(IdxNo);
1580 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 UndefElts, Depth+1);
1582 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1583
1584 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001585 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 break;
1587 }
1588 case Instruction::ShuffleVector: {
1589 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001590 uint64_t LHSVWidth =
1591 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001592 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001593 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001594 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001595 unsigned MaskVal = Shuffle->getMaskValue(i);
1596 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001597 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001598 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001599 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001600 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001601 else
Evan Cheng388df622009-02-03 10:05:09 +00001602 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001603 }
1604 }
1605 }
1606
Nate Begeman7b254672009-02-11 22:36:25 +00001607 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001608 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001609 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001610 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1611
Nate Begeman7b254672009-02-11 22:36:25 +00001612 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001613 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1614 UndefElts3, Depth+1);
1615 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1616
1617 bool NewUndefElts = false;
1618 for (unsigned i = 0; i < VWidth; i++) {
1619 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001620 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001621 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001622 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001623 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001624 NewUndefElts = true;
1625 UndefElts.set(i);
1626 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001627 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001628 if (UndefElts3[MaskVal - LHSVWidth]) {
1629 NewUndefElts = true;
1630 UndefElts.set(i);
1631 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001632 }
1633 }
1634
1635 if (NewUndefElts) {
1636 // Add additional discovered undefs.
1637 std::vector<Constant*> Elts;
1638 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001639 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001640 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001641 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001642 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001643 Shuffle->getMaskValue(i)));
1644 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001645 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001646 MadeChange = true;
1647 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001648 break;
1649 }
Chris Lattner69878332007-04-14 22:29:23 +00001650 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001651 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001652 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1653 if (!VTy) break;
1654 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001655 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001656 unsigned Ratio;
1657
1658 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001659 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001660 // elements as are demanded of us.
1661 Ratio = 1;
1662 InputDemandedElts = DemandedElts;
1663 } else if (VWidth > InVWidth) {
1664 // Untested so far.
1665 break;
1666
1667 // If there are more elements in the result than there are in the source,
1668 // then an input element is live if any of the corresponding output
1669 // elements are live.
1670 Ratio = VWidth/InVWidth;
1671 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001672 if (DemandedElts[OutIdx])
1673 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001674 }
1675 } else {
1676 // Untested so far.
1677 break;
1678
1679 // If there are more elements in the source than there are in the result,
1680 // then an input element is live if the corresponding output element is
1681 // live.
1682 Ratio = InVWidth/VWidth;
1683 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001684 if (DemandedElts[InIdx/Ratio])
1685 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001686 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001687
Chris Lattner69878332007-04-14 22:29:23 +00001688 // div/rem demand all inputs, because they don't want divide by zero.
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1690 UndefElts2, Depth+1);
1691 if (TmpV) {
1692 I->setOperand(0, TmpV);
1693 MadeChange = true;
1694 }
1695
1696 UndefElts = UndefElts2;
1697 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001698 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001699 // If there are more elements in the result than there are in the source,
1700 // then an output element is undef if the corresponding input element is
1701 // undef.
1702 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001703 if (UndefElts2[OutIdx/Ratio])
1704 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001705 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001706 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001707 // If there are more elements in the source than there are in the result,
1708 // then a result element is undef if all of the corresponding input
1709 // elements are undef.
1710 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1711 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001712 if (!UndefElts2[InIdx]) // Not undef?
1713 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001714 }
1715 break;
1716 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001717 case Instruction::And:
1718 case Instruction::Or:
1719 case Instruction::Xor:
1720 case Instruction::Add:
1721 case Instruction::Sub:
1722 case Instruction::Mul:
1723 // div/rem demand all inputs, because they don't want divide by zero.
1724 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1725 UndefElts, Depth+1);
1726 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1727 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1728 UndefElts2, Depth+1);
1729 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1730
1731 // Output elements are undefined if both are undefined. Consider things
1732 // like undef&0. The result is known zero, not undef.
1733 UndefElts &= UndefElts2;
1734 break;
1735
1736 case Instruction::Call: {
1737 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1738 if (!II) break;
1739 switch (II->getIntrinsicID()) {
1740 default: break;
1741
1742 // Binary vector operations that work column-wise. A dest element is a
1743 // function of the corresponding input elements from the two inputs.
1744 case Intrinsic::x86_sse_sub_ss:
1745 case Intrinsic::x86_sse_mul_ss:
1746 case Intrinsic::x86_sse_min_ss:
1747 case Intrinsic::x86_sse_max_ss:
1748 case Intrinsic::x86_sse2_sub_sd:
1749 case Intrinsic::x86_sse2_mul_sd:
1750 case Intrinsic::x86_sse2_min_sd:
1751 case Intrinsic::x86_sse2_max_sd:
1752 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1753 UndefElts, Depth+1);
1754 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1755 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1756 UndefElts2, Depth+1);
1757 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1758
1759 // If only the low elt is demanded and this is a scalarizable intrinsic,
1760 // scalarize it now.
1761 if (DemandedElts == 1) {
1762 switch (II->getIntrinsicID()) {
1763 default: break;
1764 case Intrinsic::x86_sse_sub_ss:
1765 case Intrinsic::x86_sse_mul_ss:
1766 case Intrinsic::x86_sse2_sub_sd:
1767 case Intrinsic::x86_sse2_mul_sd:
1768 // TODO: Lower MIN/MAX/ABS/etc
1769 Value *LHS = II->getOperand(1);
1770 Value *RHS = II->getOperand(2);
1771 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001772 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001773 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001774 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001775 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001776
1777 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001778 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001779 case Intrinsic::x86_sse_sub_ss:
1780 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001781 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001782 II->getName()), *II);
1783 break;
1784 case Intrinsic::x86_sse_mul_ss:
1785 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001786 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001787 II->getName()), *II);
1788 break;
1789 }
1790
1791 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001792 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001793 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001794 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001795 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001796 return New;
1797 }
1798 }
1799
1800 // Output elements are undefined if both are undefined. Consider things
1801 // like undef&0. The result is known zero, not undef.
1802 UndefElts &= UndefElts2;
1803 break;
1804 }
1805 break;
1806 }
1807 }
1808 return MadeChange ? I : 0;
1809}
1810
Dan Gohman45b4e482008-05-19 22:14:15 +00001811
Chris Lattner564a7272003-08-13 19:01:45 +00001812/// AssociativeOpt - Perform an optimization on an associative operator. This
1813/// function is designed to check a chain of associative operators for a
1814/// potential to apply a certain optimization. Since the optimization may be
1815/// applicable if the expression was reassociated, this checks the chain, then
1816/// reassociates the expression as necessary to expose the optimization
1817/// opportunity. This makes use of a special Functor, which must define
1818/// 'shouldApply' and 'apply' methods.
1819///
1820template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001821static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001822 unsigned Opcode = Root.getOpcode();
1823 Value *LHS = Root.getOperand(0);
1824
1825 // Quick check, see if the immediate LHS matches...
1826 if (F.shouldApply(LHS))
1827 return F.apply(Root);
1828
1829 // Otherwise, if the LHS is not of the same opcode as the root, return.
1830 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001831 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001832 // Should we apply this transform to the RHS?
1833 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1834
1835 // If not to the RHS, check to see if we should apply to the LHS...
1836 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1837 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1838 ShouldApply = true;
1839 }
1840
1841 // If the functor wants to apply the optimization to the RHS of LHSI,
1842 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1843 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001844 // Now all of the instructions are in the current basic block, go ahead
1845 // and perform the reassociation.
1846 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1847
1848 // First move the selected RHS to the LHS of the root...
1849 Root.setOperand(0, LHSI->getOperand(1));
1850
1851 // Make what used to be the LHS of the root be the user of the root...
1852 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001853 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001854 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001855 return 0;
1856 }
Chris Lattner65725312004-04-16 18:08:07 +00001857 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001858 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001859 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001860 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001861 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001862
1863 // Now propagate the ExtraOperand down the chain of instructions until we
1864 // get to LHSI.
1865 while (TmpLHSI != LHSI) {
1866 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001867 // Move the instruction to immediately before the chain we are
1868 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001869 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001870 ARI = NextLHSI;
1871
Chris Lattner564a7272003-08-13 19:01:45 +00001872 Value *NextOp = NextLHSI->getOperand(1);
1873 NextLHSI->setOperand(1, ExtraOperand);
1874 TmpLHSI = NextLHSI;
1875 ExtraOperand = NextOp;
1876 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001877
Chris Lattner564a7272003-08-13 19:01:45 +00001878 // Now that the instructions are reassociated, have the functor perform
1879 // the transformation...
1880 return F.apply(Root);
1881 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001882
Chris Lattner564a7272003-08-13 19:01:45 +00001883 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1884 }
1885 return 0;
1886}
1887
Dan Gohman844731a2008-05-13 00:00:25 +00001888namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001889
Nick Lewycky02d639f2008-05-23 04:34:58 +00001890// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001891struct AddRHS {
1892 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001893 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001894 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1895 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001896 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001897 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001898 }
1899};
1900
1901// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1902// iff C1&C2 == 0
1903struct AddMaskingAnd {
1904 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001905 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001906 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001907 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001908 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001909 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001910 }
1911 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001912 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001913 }
1914};
1915
Dan Gohman844731a2008-05-13 00:00:25 +00001916}
1917
Chris Lattner6e7ba452005-01-01 16:22:27 +00001918static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001919 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001920 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001921 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001922
Chris Lattner2eefe512004-04-09 19:05:30 +00001923 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001924 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1925 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001926
Chris Lattner2eefe512004-04-09 19:05:30 +00001927 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1928 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001929 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1930 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001931 }
1932
1933 Value *Op0 = SO, *Op1 = ConstOperand;
1934 if (!ConstIsRHS)
1935 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001936
Chris Lattner6e7ba452005-01-01 16:22:27 +00001937 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001938 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1939 SO->getName()+".op");
1940 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1941 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1942 SO->getName()+".cmp");
1943 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1944 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1945 SO->getName()+".cmp");
1946 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001947}
1948
1949// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1950// constant as the other operand, try to fold the binary operator into the
1951// select arguments. This also works for Cast instructions, which obviously do
1952// not have a second operand.
1953static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1954 InstCombiner *IC) {
1955 // Don't modify shared select instructions
1956 if (!SI->hasOneUse()) return 0;
1957 Value *TV = SI->getOperand(1);
1958 Value *FV = SI->getOperand(2);
1959
1960 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001961 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001962 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001963
Chris Lattner6e7ba452005-01-01 16:22:27 +00001964 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1965 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1966
Gabor Greif051a9502008-04-06 20:25:17 +00001967 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1968 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001969 }
1970 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001971}
1972
Chris Lattner4e998b22004-09-29 05:07:12 +00001973
Chris Lattner5d1704d2009-09-27 19:57:57 +00001974/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1975/// has a PHI node as operand #0, see if we can fold the instruction into the
1976/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00001977///
1978/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1979/// that would normally be unprofitable because they strongly encourage jump
1980/// threading.
1981Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1982 bool AllowAggressive) {
1983 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00001984 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001985 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00001986 if (NumPHIValues == 0 ||
1987 // We normally only transform phis with a single use, unless we're trying
1988 // hard to make jump threading happen.
1989 (!PN->hasOneUse() && !AllowAggressive))
1990 return 0;
1991
1992
Chris Lattner5d1704d2009-09-27 19:57:57 +00001993 // Check to see if all of the operands of the PHI are simple constants
1994 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001995 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1996 // bail out. We don't do arbitrary constant expressions here because moving
1997 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001998 BasicBlock *NonConstBB = 0;
1999 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002000 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2001 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002003 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004 NonConstBB = PN->getIncomingBlock(i);
2005
2006 // If the incoming non-constant value is in I's block, we have an infinite
2007 // loop.
2008 if (NonConstBB == I.getParent())
2009 return 0;
2010 }
2011
2012 // If there is exactly one non-constant value, we can insert a copy of the
2013 // operation in that block. However, if this is a critical edge, we would be
2014 // inserting the computation one some other paths (e.g. inside a loop). Only
2015 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002016 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2018 if (!BI || !BI->isUnconditional()) return 0;
2019 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002020
2021 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002022 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002023 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002024 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002025 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002026
2027 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002028 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2029 // We only currently try to fold the condition of a select when it is a phi,
2030 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002031 Value *TrueV = SI->getTrueValue();
2032 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002033 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002034 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002035 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002036 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2037 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002038 Value *InV = 0;
2039 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002040 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002041 } else {
2042 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002043 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2044 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002045 "phitmp", NonConstBB->getTerminator());
2046 Worklist.Add(cast<Instruction>(InV));
2047 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002048 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002049 }
2050 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002051 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002052 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002053 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002054 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002055 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002056 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002057 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002058 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002059 } else {
2060 assert(PN->getIncomingBlock(i) == NonConstBB);
2061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002062 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002063 PN->getIncomingValue(i), C, "phitmp",
2064 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002065 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002066 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002067 CI->getPredicate(),
2068 PN->getIncomingValue(i), C, "phitmp",
2069 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002070 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002071 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002072
Chris Lattner7a1e9242009-08-30 06:13:40 +00002073 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002074 }
2075 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002076 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002077 } else {
2078 CastInst *CI = cast<CastInst>(&I);
2079 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002080 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002081 Value *InV;
2082 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002083 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002084 } else {
2085 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002086 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002087 I.getType(), "phitmp",
2088 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002089 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002090 }
2091 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002092 }
2093 }
2094 return ReplaceInstUsesWith(I, NewPN);
2095}
2096
Chris Lattner2454a2e2008-01-29 06:52:45 +00002097
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002098/// WillNotOverflowSignedAdd - Return true if we can prove that:
2099/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2100/// This basically requires proving that the add in the original type would not
2101/// overflow to change the sign bit or have a carry out.
2102bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2103 // There are different heuristics we can use for this. Here are some simple
2104 // ones.
2105
2106 // Add has the property that adding any two 2's complement numbers can only
2107 // have one carry bit which can change a sign. As such, if LHS and RHS each
2108 // have at least two sign bits, we know that the addition of the two values will
2109 // sign extend fine.
2110 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2111 return true;
2112
2113
2114 // If one of the operands only has one non-zero bit, and if the other operand
2115 // has a known-zero bit in a more significant place than it (not including the
2116 // sign bit) the ripple may go up to and fill the zero, but won't change the
2117 // sign. For example, (X & ~4) + 1.
2118
2119 // TODO: Implement.
2120
2121 return false;
2122}
2123
Chris Lattner2454a2e2008-01-29 06:52:45 +00002124
Chris Lattner7e708292002-06-25 16:13:24 +00002125Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002126 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002127 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002128
Chris Lattner66331a42004-04-10 22:01:55 +00002129 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002130 // X + undef -> undef
2131 if (isa<UndefValue>(RHS))
2132 return ReplaceInstUsesWith(I, RHS);
2133
Chris Lattner66331a42004-04-10 22:01:55 +00002134 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002135 if (RHSC->isNullValue())
2136 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002137
Chris Lattner66331a42004-04-10 22:01:55 +00002138 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002139 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002140 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002141 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002142 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002143 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002144
2145 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2146 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002147 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002148 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002149
Eli Friedman709b33d2009-07-13 22:27:52 +00002150 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002151 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002152 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002153 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002154 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002155
2156 if (isa<PHINode>(LHS))
2157 if (Instruction *NV = FoldOpIntoPhi(I))
2158 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002159
Chris Lattner4f637d42006-01-06 17:59:59 +00002160 ConstantInt *XorRHS = 0;
2161 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002162 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002163 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002164 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002165 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002166
Zhou Sheng4351c642007-04-02 08:20:41 +00002167 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002168 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2169 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002170 do {
2171 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002172 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2173 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002174 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2175 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002176 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002177 if (!MaskedValueIsZero(XorLHS,
2178 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002179 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002180 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002181 }
2182 }
2183 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002184 C0080Val = APIntOps::lshr(C0080Val, Size);
2185 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2186 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002187
Reid Spencer35c38852007-03-28 01:36:16 +00002188 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002189 // with funny bit widths then this switch statement should be removed. It
2190 // is just here to get the size of the "middle" type back up to something
2191 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002192 const Type *MiddleType = 0;
2193 switch (Size) {
2194 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002195 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2196 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2197 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002198 }
2199 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002200 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002201 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002202 }
2203 }
Chris Lattner66331a42004-04-10 22:01:55 +00002204 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002205
Owen Anderson1d0be152009-08-13 21:58:54 +00002206 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002207 return BinaryOperator::CreateXor(LHS, RHS);
2208
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002209 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002210 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002211 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002212 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002213
2214 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2215 if (RHSI->getOpcode() == Instruction::Sub)
2216 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2217 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2218 }
2219 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2220 if (LHSI->getOpcode() == Instruction::Sub)
2221 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2222 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2223 }
Robert Bocchino71698282004-07-27 21:02:21 +00002224 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002225
Chris Lattner5c4afb92002-05-08 22:46:53 +00002226 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002227 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002228 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002229 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002230 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002231 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002232 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002233 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002234 }
2235
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002236 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002237 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002238
2239 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002240 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002241 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002242 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002243
Misha Brukmanfd939082005-04-21 23:48:37 +00002244
Chris Lattner50af16a2004-11-13 19:50:12 +00002245 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002246 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002247 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002248 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002249
2250 // X*C1 + X*C2 --> X * (C1+C2)
2251 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002252 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002253 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002254 }
2255
2256 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002257 if (dyn_castFoldableMul(RHS, C2) == LHS)
2258 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002259
Chris Lattnere617c9e2007-01-05 02:17:46 +00002260 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002261 if (dyn_castNotVal(LHS) == RHS ||
2262 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002263 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002264
Chris Lattnerad3448c2003-02-18 19:57:07 +00002265
Chris Lattner564a7272003-08-13 19:01:45 +00002266 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002267 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2268 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002269 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002270
2271 // A+B --> A|B iff A and B have no bits set in common.
2272 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2273 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2274 APInt LHSKnownOne(IT->getBitWidth(), 0);
2275 APInt LHSKnownZero(IT->getBitWidth(), 0);
2276 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2277 if (LHSKnownZero != 0) {
2278 APInt RHSKnownOne(IT->getBitWidth(), 0);
2279 APInt RHSKnownZero(IT->getBitWidth(), 0);
2280 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2281
2282 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002283 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002284 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002285 }
2286 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002287
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002288 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002289 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002290 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002291 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2292 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002293 if (W != Y) {
2294 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002295 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002296 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002297 std::swap(W, X);
2298 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002299 std::swap(Y, Z);
2300 std::swap(W, X);
2301 }
2302 }
2303
2304 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002305 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002306 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002307 }
2308 }
2309 }
2310
Chris Lattner6b032052003-10-02 15:11:26 +00002311 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002312 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002313 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002314 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002315
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002316 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002317 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002318 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002319 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002320 if (Anded == CRHS) {
2321 // See if all bits from the first bit set in the Add RHS up are included
2322 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002323 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002324
2325 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002326 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002327
2328 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002329 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002330
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002331 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2332 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002333 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002334 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002335 }
2336 }
2337 }
2338
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002339 // Try to fold constant add into select arguments.
2340 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002341 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002342 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002343 }
2344
Chris Lattner42790482007-12-20 01:56:58 +00002345 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002346 {
2347 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002348 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002349 if (!SI) {
2350 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002351 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002352 }
Chris Lattner42790482007-12-20 01:56:58 +00002353 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002354 Value *TV = SI->getTrueValue();
2355 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002356 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002357
2358 // Can we fold the add into the argument of the select?
2359 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002360 if (match(FV, m_Zero()) &&
2361 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002362 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002363 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002364 if (match(TV, m_Zero()) &&
2365 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002366 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002367 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002368 }
2369 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002370
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002371 // Check for (add (sext x), y), see if we can merge this into an
2372 // integer add followed by a sext.
2373 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2374 // (add (sext x), cst) --> (sext (add x, cst'))
2375 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2376 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002377 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002378 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002379 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002380 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2381 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002382 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2383 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002384 return new SExtInst(NewAdd, I.getType());
2385 }
2386 }
2387
2388 // (add (sext x), (sext y)) --> (sext (add int x, y))
2389 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2390 // Only do this if x/y have the same type, if at last one of them has a
2391 // single use (so we don't increase the number of sexts), and if the
2392 // integer add will not overflow.
2393 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2394 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2395 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2396 RHSConv->getOperand(0))) {
2397 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002398 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2399 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002400 return new SExtInst(NewAdd, I.getType());
2401 }
2402 }
2403 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002404
2405 return Changed ? &I : 0;
2406}
2407
2408Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2409 bool Changed = SimplifyCommutative(I);
2410 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2411
2412 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2413 // X + 0 --> X
2414 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002415 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002416 (I.getType())->getValueAPF()))
2417 return ReplaceInstUsesWith(I, LHS);
2418 }
2419
2420 if (isa<PHINode>(LHS))
2421 if (Instruction *NV = FoldOpIntoPhi(I))
2422 return NV;
2423 }
2424
2425 // -A + B --> B - A
2426 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002427 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002428 return BinaryOperator::CreateFSub(RHS, LHSV);
2429
2430 // A + -B --> A - B
2431 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002432 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002433 return BinaryOperator::CreateFSub(LHS, V);
2434
2435 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2436 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2437 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2438 return ReplaceInstUsesWith(I, LHS);
2439
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002440 // Check for (add double (sitofp x), y), see if we can merge this into an
2441 // integer add followed by a promotion.
2442 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2443 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2444 // ... if the constant fits in the integer value. This is useful for things
2445 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2446 // requires a constant pool load, and generally allows the add to be better
2447 // instcombined.
2448 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2449 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002450 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002451 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002452 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002453 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2454 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002455 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2456 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002457 return new SIToFPInst(NewAdd, I.getType());
2458 }
2459 }
2460
2461 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2462 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2463 // Only do this if x/y have the same type, if at last one of them has a
2464 // single use (so we don't increase the number of int->fp conversions),
2465 // and if the integer add will not overflow.
2466 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2467 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2468 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2469 RHSConv->getOperand(0))) {
2470 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002471 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2472 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002473 return new SIToFPInst(NewAdd, I.getType());
2474 }
2475 }
2476 }
2477
Chris Lattner7e708292002-06-25 16:13:24 +00002478 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002479}
2480
Chris Lattner7e708292002-06-25 16:13:24 +00002481Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002483
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002484 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002485 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002486
Chris Lattner233f7dc2002-08-12 21:17:25 +00002487 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002488 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002489 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002490
Chris Lattnere87597f2004-10-16 18:11:37 +00002491 if (isa<UndefValue>(Op0))
2492 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2493 if (isa<UndefValue>(Op1))
2494 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2495
Chris Lattnerd65460f2003-11-05 01:06:05 +00002496 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2497 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002498 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002499 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002500
Chris Lattnerd65460f2003-11-05 01:06:05 +00002501 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002502 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002503 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002504 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002505
Chris Lattner76b7a062007-01-15 07:02:54 +00002506 // -(X >>u 31) -> (X >>s 31)
2507 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002508 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002509 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002510 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002511 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002512 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002513 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002514 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002515 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002517 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002518 }
2519 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002520 }
2521 else if (SI->getOpcode() == Instruction::AShr) {
2522 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2523 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002524 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002525 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002526 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002527 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002528 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002529 }
2530 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002531 }
2532 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002533 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002534
2535 // Try to fold constant sub into select arguments.
2536 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002537 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002538 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002539
2540 // C - zext(bool) -> bool ? C - 1 : C
2541 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002542 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002543 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002544 }
2545
Owen Anderson1d0be152009-08-13 21:58:54 +00002546 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002547 return BinaryOperator::CreateXor(Op0, Op1);
2548
Chris Lattner43d84d62005-04-07 16:15:25 +00002549 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002550 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002551 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002552 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002553 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002554 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002555 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002556 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002557 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2558 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2559 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002560 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002561 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002562 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002563 }
2564
Chris Lattnerfd059242003-10-15 16:48:29 +00002565 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002566 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2567 // is not used by anyone else...
2568 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002569 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002570 // Swap the two operands of the subexpr...
2571 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2572 Op1I->setOperand(0, IIOp1);
2573 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002574
Chris Lattnera2881962003-02-18 19:28:33 +00002575 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002577 }
2578
2579 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2580 //
2581 if (Op1I->getOpcode() == Instruction::And &&
2582 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2583 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2584
Chris Lattner74381062009-08-30 07:44:24 +00002585 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002586 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002587 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002588
Reid Spencerac5209e2006-10-16 23:08:08 +00002589 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002590 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002591 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002592 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002593 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002594 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002595 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002596
Chris Lattnerad3448c2003-02-18 19:57:07 +00002597 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002598 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002599 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002600 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002601 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002602 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002603 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002604 }
Chris Lattner40371712002-05-09 01:29:19 +00002605 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002606 }
Chris Lattnera2881962003-02-18 19:28:33 +00002607
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002608 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2609 if (Op0I->getOpcode() == Instruction::Add) {
2610 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2611 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2612 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2613 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2614 } else if (Op0I->getOpcode() == Instruction::Sub) {
2615 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002616 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002617 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002618 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002619 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002620
Chris Lattner50af16a2004-11-13 19:50:12 +00002621 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002622 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002623 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002624 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002625
Chris Lattner50af16a2004-11-13 19:50:12 +00002626 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002627 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002628 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002629 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002630 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002631}
2632
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002633Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2634 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2635
2636 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002637 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002638 return BinaryOperator::CreateFAdd(Op0, V);
2639
2640 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2641 if (Op1I->getOpcode() == Instruction::FAdd) {
2642 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002643 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002644 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002645 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002646 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002647 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002648 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002649 }
2650
2651 return 0;
2652}
2653
Chris Lattnera0141b92007-07-15 20:42:37 +00002654/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2655/// comparison only checks the sign bit. If it only checks the sign bit, set
2656/// TrueIfSigned if the result of the comparison is true when the input value is
2657/// signed.
2658static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2659 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002660 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002661 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2662 TrueIfSigned = true;
2663 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002664 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2665 TrueIfSigned = true;
2666 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002667 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2668 TrueIfSigned = false;
2669 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002670 case ICmpInst::ICMP_UGT:
2671 // True if LHS u> RHS and RHS == high-bit-mask - 1
2672 TrueIfSigned = true;
2673 return RHS->getValue() ==
2674 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2675 case ICmpInst::ICMP_UGE:
2676 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2677 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002678 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002679 default:
2680 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002681 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002682}
2683
Chris Lattner7e708292002-06-25 16:13:24 +00002684Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002685 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002687
Chris Lattnera2498472009-10-11 21:36:10 +00002688 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002689 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002690
Chris Lattner8af304a2009-10-11 07:53:15 +00002691 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002692 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2693 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002694
2695 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002696 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002697 if (SI->getOpcode() == Instruction::Shl)
2698 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002699 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002700 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002701
Zhou Sheng843f07672007-04-19 05:39:12 +00002702 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002703 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002704 if (CI->equalsInt(1)) // X * 1 == X
2705 return ReplaceInstUsesWith(I, Op0);
2706 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002707 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002708
Zhou Sheng97b52c22007-03-29 01:57:21 +00002709 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002710 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002711 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002712 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002713 }
Chris Lattnera2498472009-10-11 21:36:10 +00002714 } else if (isa<VectorType>(Op1C->getType())) {
2715 if (Op1C->isNullValue())
2716 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002717
Chris Lattnera2498472009-10-11 21:36:10 +00002718 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002719 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002720 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002721
2722 // As above, vector X*splat(1.0) -> X in all defined cases.
2723 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002724 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2725 if (CI->equalsInt(1))
2726 return ReplaceInstUsesWith(I, Op0);
2727 }
2728 }
Chris Lattnera2881962003-02-18 19:28:33 +00002729 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002730
2731 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2732 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002733 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002734 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002735 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2736 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002737 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002738
2739 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002740
2741 // Try to fold constant mul into select arguments.
2742 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002743 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002744 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002745
2746 if (isa<PHINode>(Op0))
2747 if (Instruction *NV = FoldOpIntoPhi(I))
2748 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002749 }
2750
Dan Gohman186a6362009-08-12 16:04:34 +00002751 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002752 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002753 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002754
Nick Lewycky0c730792008-11-21 07:33:58 +00002755 // (X / Y) * Y = X - (X % Y)
2756 // (X / Y) * -Y = (X % Y) - X
2757 {
Chris Lattnera2498472009-10-11 21:36:10 +00002758 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002759 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2760 if (!BO ||
2761 (BO->getOpcode() != Instruction::UDiv &&
2762 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002763 Op1C = Op0;
2764 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002765 }
Chris Lattnera2498472009-10-11 21:36:10 +00002766 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002767 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002768 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002769 (BO->getOpcode() == Instruction::UDiv ||
2770 BO->getOpcode() == Instruction::SDiv)) {
2771 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2772
Dan Gohmanfa94b942009-08-12 16:33:09 +00002773 // If the division is exact, X % Y is zero.
2774 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2775 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002776 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002777 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002778 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002779 }
2780
Chris Lattner74381062009-08-30 07:44:24 +00002781 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002782 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002783 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002784 else
Chris Lattner74381062009-08-30 07:44:24 +00002785 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002786 Rem->takeName(BO);
2787
Chris Lattnera2498472009-10-11 21:36:10 +00002788 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002789 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002790 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002791 }
2792 }
2793
Chris Lattner8af304a2009-10-11 07:53:15 +00002794 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002795 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002796 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002797
Chris Lattner8af304a2009-10-11 07:53:15 +00002798 // X*(1 << Y) --> X << Y
2799 // (1 << Y)*X --> X << Y
2800 {
2801 Value *Y;
2802 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002803 return BinaryOperator::CreateShl(Op1, Y);
2804 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002805 return BinaryOperator::CreateShl(Op0, Y);
2806 }
2807
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002808 // If one of the operands of the multiply is a cast from a boolean value, then
2809 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002810 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2811 if (!isa<VectorType>(I.getType())) {
2812 // -2 is "-1 << 1" so it is all bits set except the low one.
2813 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), -2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002814
Chris Lattnerd2c58362009-10-11 21:29:45 +00002815 Value *BoolCast = 0, *OtherOp = 0;
2816 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002817 BoolCast = Op0, OtherOp = Op1;
2818 else if (MaskedValueIsZero(Op1, Negative2))
2819 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002820
Chris Lattner0036e3a2009-10-11 21:22:21 +00002821 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002822 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2823 BoolCast, "tmp");
2824 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002825 }
2826 }
2827
Chris Lattner7e708292002-06-25 16:13:24 +00002828 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002829}
2830
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002831Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2832 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002833 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002834
2835 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002836 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2837 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002838 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2839 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2840 if (Op1F->isExactlyValue(1.0))
2841 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002842 } else if (isa<VectorType>(Op1C->getType())) {
2843 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002844 // As above, vector X*splat(1.0) -> X in all defined cases.
2845 if (Constant *Splat = Op1V->getSplatValue()) {
2846 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2847 if (F->isExactlyValue(1.0))
2848 return ReplaceInstUsesWith(I, Op0);
2849 }
2850 }
2851 }
2852
2853 // Try to fold constant mul into select arguments.
2854 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2855 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2856 return R;
2857
2858 if (isa<PHINode>(Op0))
2859 if (Instruction *NV = FoldOpIntoPhi(I))
2860 return NV;
2861 }
2862
Dan Gohman186a6362009-08-12 16:04:34 +00002863 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002864 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002865 return BinaryOperator::CreateFMul(Op0v, Op1v);
2866
2867 return Changed ? &I : 0;
2868}
2869
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002870/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2871/// instruction.
2872bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2873 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2874
2875 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2876 int NonNullOperand = -1;
2877 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2878 if (ST->isNullValue())
2879 NonNullOperand = 2;
2880 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2881 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2882 if (ST->isNullValue())
2883 NonNullOperand = 1;
2884
2885 if (NonNullOperand == -1)
2886 return false;
2887
2888 Value *SelectCond = SI->getOperand(0);
2889
2890 // Change the div/rem to use 'Y' instead of the select.
2891 I.setOperand(1, SI->getOperand(NonNullOperand));
2892
2893 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2894 // problem. However, the select, or the condition of the select may have
2895 // multiple uses. Based on our knowledge that the operand must be non-zero,
2896 // propagate the known value for the select into other uses of it, and
2897 // propagate a known value of the condition into its other users.
2898
2899 // If the select and condition only have a single use, don't bother with this,
2900 // early exit.
2901 if (SI->use_empty() && SelectCond->hasOneUse())
2902 return true;
2903
2904 // Scan the current block backward, looking for other uses of SI.
2905 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2906
2907 while (BBI != BBFront) {
2908 --BBI;
2909 // If we found a call to a function, we can't assume it will return, so
2910 // information from below it cannot be propagated above it.
2911 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2912 break;
2913
2914 // Replace uses of the select or its condition with the known values.
2915 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2916 I != E; ++I) {
2917 if (*I == SI) {
2918 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002919 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002920 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002921 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2922 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002923 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002924 }
2925 }
2926
2927 // If we past the instruction, quit looking for it.
2928 if (&*BBI == SI)
2929 SI = 0;
2930 if (&*BBI == SelectCond)
2931 SelectCond = 0;
2932
2933 // If we ran out of things to eliminate, break out of the loop.
2934 if (SelectCond == 0 && SI == 0)
2935 break;
2936
2937 }
2938 return true;
2939}
2940
2941
Reid Spencer1628cec2006-10-26 06:15:43 +00002942/// This function implements the transforms on div instructions that work
2943/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2944/// used by the visitors to those instructions.
2945/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002946Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002947 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002948
Chris Lattner50b2ca42008-02-19 06:12:18 +00002949 // undef / X -> 0 for integer.
2950 // undef / X -> undef for FP (the undef could be a snan).
2951 if (isa<UndefValue>(Op0)) {
2952 if (Op0->getType()->isFPOrFPVector())
2953 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002955 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002956
2957 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002958 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002959 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002960
Reid Spencer1628cec2006-10-26 06:15:43 +00002961 return 0;
2962}
Misha Brukmanfd939082005-04-21 23:48:37 +00002963
Reid Spencer1628cec2006-10-26 06:15:43 +00002964/// This function implements the transforms common to both integer division
2965/// instructions (udiv and sdiv). It is called by the visitors to those integer
2966/// division instructions.
2967/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002968Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002969 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2970
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002971 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002972 if (Op0 == Op1) {
2973 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002974 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002975 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002976 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002977 }
2978
Owen Andersoneed707b2009-07-24 23:12:02 +00002979 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002980 return ReplaceInstUsesWith(I, CI);
2981 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002982
Reid Spencer1628cec2006-10-26 06:15:43 +00002983 if (Instruction *Common = commonDivTransforms(I))
2984 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002985
2986 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2987 // This does not apply for fdiv.
2988 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2989 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002990
2991 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2992 // div X, 1 == X
2993 if (RHS->equalsInt(1))
2994 return ReplaceInstUsesWith(I, Op0);
2995
2996 // (X / C1) / C2 -> X / (C1*C2)
2997 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2998 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2999 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003000 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003001 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003002 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003003 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003004 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003005 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003006 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003007
Reid Spencerbca0e382007-03-23 20:05:17 +00003008 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003009 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3010 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3011 return R;
3012 if (isa<PHINode>(Op0))
3013 if (Instruction *NV = FoldOpIntoPhi(I))
3014 return NV;
3015 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003016 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003017
Chris Lattnera2881962003-02-18 19:28:33 +00003018 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003019 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003020 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003021 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003022
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003023 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003024 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003025 return ReplaceInstUsesWith(I, Op0);
3026
Nick Lewycky895f0852008-11-27 20:21:08 +00003027 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3028 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3029 // div X, 1 == X
3030 if (X->isOne())
3031 return ReplaceInstUsesWith(I, Op0);
3032 }
3033
Reid Spencer1628cec2006-10-26 06:15:43 +00003034 return 0;
3035}
3036
3037Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3038 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3039
3040 // Handle the integer div common cases
3041 if (Instruction *Common = commonIDivTransforms(I))
3042 return Common;
3043
Reid Spencer1628cec2006-10-26 06:15:43 +00003044 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003045 // X udiv C^2 -> X >> C
3046 // Check to see if this is an unsigned division with an exact power of 2,
3047 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003048 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003049 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003050 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003051
3052 // X udiv C, where C >= signbit
3053 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003054 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003055 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003056 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003057 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003058 }
3059
3060 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003061 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 if (RHSI->getOpcode() == Instruction::Shl &&
3063 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003064 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003065 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003066 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003067 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003068 if (uint32_t C2 = C1.logBase2())
3069 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003070 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003071 }
3072 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003073 }
3074
Reid Spencer1628cec2006-10-26 06:15:43 +00003075 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3076 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003077 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003079 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003080 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003081 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003082 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003083 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003084 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003085 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003086 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003087
3088 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003089 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003090 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003091
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003092 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003093 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003094 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003095 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003096 return 0;
3097}
3098
Reid Spencer1628cec2006-10-26 06:15:43 +00003099Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3101
3102 // Handle the integer div common cases
3103 if (Instruction *Common = commonIDivTransforms(I))
3104 return Common;
3105
3106 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3107 // sdiv X, -1 == -X
3108 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003109 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003110
Dan Gohmanfa94b942009-08-12 16:33:09 +00003111 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003112 if (cast<SDivOperator>(&I)->isExact() &&
3113 RHS->getValue().isNonNegative() &&
3114 RHS->getValue().isPowerOf2()) {
3115 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3116 RHS->getValue().exactLogBase2());
3117 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3118 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003119
3120 // -X/C --> X/-C provided the negation doesn't overflow.
3121 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3122 if (isa<Constant>(Sub->getOperand(0)) &&
3123 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003124 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003125 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3126 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003127 }
3128
3129 // If the sign bits of both operands are zero (i.e. we can prove they are
3130 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003131 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003132 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003133 if (MaskedValueIsZero(Op0, Mask)) {
3134 if (MaskedValueIsZero(Op1, Mask)) {
3135 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3136 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3137 }
3138 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003139 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003140 ShiftedInt->getValue().isPowerOf2()) {
3141 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3142 // Safe because the only negative value (1 << Y) can take on is
3143 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3144 // the sign bit set.
3145 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3146 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003147 }
Eli Friedman8be17392009-07-18 09:53:21 +00003148 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003149
3150 return 0;
3151}
3152
3153Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3154 return commonDivTransforms(I);
3155}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003156
Reid Spencer0a783f72006-11-02 01:53:59 +00003157/// This function implements the transforms on rem instructions that work
3158/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3159/// is used by the visitors to those instructions.
3160/// @brief Transforms common to all three rem instructions
3161Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003162 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003163
Chris Lattner50b2ca42008-02-19 06:12:18 +00003164 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3165 if (I.getType()->isFPOrFPVector())
3166 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003168 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003169 if (isa<UndefValue>(Op1))
3170 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003171
3172 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003173 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3174 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003175
Reid Spencer0a783f72006-11-02 01:53:59 +00003176 return 0;
3177}
3178
3179/// This function implements the transforms common to both integer remainder
3180/// instructions (urem and srem). It is called by the visitors to those integer
3181/// remainder instructions.
3182/// @brief Common integer remainder transforms
3183Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3184 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3185
3186 if (Instruction *common = commonRemTransforms(I))
3187 return common;
3188
Dale Johannesened6af242009-01-21 00:35:19 +00003189 // 0 % X == 0 for integer, we don't need to preserve faults!
3190 if (Constant *LHS = dyn_cast<Constant>(Op0))
3191 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003192 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003193
Chris Lattner857e8cd2004-12-12 21:48:58 +00003194 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003195 // X % 0 == undef, we don't need to preserve faults!
3196 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003197 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003198
Chris Lattnera2881962003-02-18 19:28:33 +00003199 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003200 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003201
Chris Lattner97943922006-02-28 05:49:21 +00003202 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3203 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3204 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3205 return R;
3206 } else if (isa<PHINode>(Op0I)) {
3207 if (Instruction *NV = FoldOpIntoPhi(I))
3208 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003209 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003210
3211 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003212 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003213 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003214 }
Chris Lattnera2881962003-02-18 19:28:33 +00003215 }
3216
Reid Spencer0a783f72006-11-02 01:53:59 +00003217 return 0;
3218}
3219
3220Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3221 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3222
3223 if (Instruction *common = commonIRemTransforms(I))
3224 return common;
3225
3226 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3227 // X urem C^2 -> X and C
3228 // Check to see if this is an unsigned remainder with an exact power of 2,
3229 // if so, convert to a bitwise and.
3230 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003231 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003232 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 }
3234
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003235 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003236 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3237 if (RHSI->getOpcode() == Instruction::Shl &&
3238 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003239 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003240 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003241 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003242 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003243 }
3244 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003246
Reid Spencer0a783f72006-11-02 01:53:59 +00003247 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3248 // where C1&C2 are powers of two.
3249 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3250 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3251 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3252 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003253 if ((STO->getValue().isPowerOf2()) &&
3254 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003255 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3256 SI->getName()+".t");
3257 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3258 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003259 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003260 }
3261 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003262 }
3263
Chris Lattner3f5b8772002-05-06 16:14:14 +00003264 return 0;
3265}
3266
Reid Spencer0a783f72006-11-02 01:53:59 +00003267Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3268 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3269
Dan Gohmancff55092007-11-05 23:16:33 +00003270 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003271 if (Instruction *Common = commonIRemTransforms(I))
3272 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003273
Dan Gohman186a6362009-08-12 16:04:34 +00003274 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003275 if (!isa<Constant>(RHSNeg) ||
3276 (isa<ConstantInt>(RHSNeg) &&
3277 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003278 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003279 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003280 I.setOperand(1, RHSNeg);
3281 return &I;
3282 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003283
Dan Gohmancff55092007-11-05 23:16:33 +00003284 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003285 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003286 if (I.getType()->isInteger()) {
3287 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3288 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3289 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003290 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003291 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003292 }
3293
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003294 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003295 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3296 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003297
Nick Lewycky9dce8732008-12-20 16:48:00 +00003298 bool hasNegative = false;
3299 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3300 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3301 if (RHS->getValue().isNegative())
3302 hasNegative = true;
3303
3304 if (hasNegative) {
3305 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003306 for (unsigned i = 0; i != VWidth; ++i) {
3307 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3308 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003309 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003310 else
3311 Elts[i] = RHS;
3312 }
3313 }
3314
Owen Andersonaf7ec972009-07-28 21:19:26 +00003315 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003316 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003317 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003318 I.setOperand(1, NewRHSV);
3319 return &I;
3320 }
3321 }
3322 }
3323
Reid Spencer0a783f72006-11-02 01:53:59 +00003324 return 0;
3325}
3326
3327Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003328 return commonRemTransforms(I);
3329}
3330
Chris Lattner457dd822004-06-09 07:59:58 +00003331// isOneBitSet - Return true if there is exactly one bit set in the specified
3332// constant.
3333static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003334 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003335}
3336
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003337// isHighOnes - Return true if the constant is of the form 1+0+.
3338// This is the same as lowones(~X).
3339static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003340 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003341}
3342
Reid Spencere4d87aa2006-12-23 06:05:41 +00003343/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003344/// are carefully arranged to allow folding of expressions such as:
3345///
3346/// (A < B) | (A > B) --> (A != B)
3347///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003348/// Note that this is only valid if the first and second predicates have the
3349/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003350///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351/// Three bits are used to represent the condition, as follows:
3352/// 0 A > B
3353/// 1 A == B
3354/// 2 A < B
3355///
3356/// <=> Value Definition
3357/// 000 0 Always false
3358/// 001 1 A > B
3359/// 010 2 A == B
3360/// 011 3 A >= B
3361/// 100 4 A < B
3362/// 101 5 A != B
3363/// 110 6 A <= B
3364/// 111 7 Always true
3365///
3366static unsigned getICmpCode(const ICmpInst *ICI) {
3367 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003368 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003369 case ICmpInst::ICMP_UGT: return 1; // 001
3370 case ICmpInst::ICMP_SGT: return 1; // 001
3371 case ICmpInst::ICMP_EQ: return 2; // 010
3372 case ICmpInst::ICMP_UGE: return 3; // 011
3373 case ICmpInst::ICMP_SGE: return 3; // 011
3374 case ICmpInst::ICMP_ULT: return 4; // 100
3375 case ICmpInst::ICMP_SLT: return 4; // 100
3376 case ICmpInst::ICMP_NE: return 5; // 101
3377 case ICmpInst::ICMP_ULE: return 6; // 110
3378 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003379 // True -> 7
3380 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003381 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003382 return 0;
3383 }
3384}
3385
Evan Cheng8db90722008-10-14 17:15:11 +00003386/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3387/// predicate into a three bit mask. It also returns whether it is an ordered
3388/// predicate by reference.
3389static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3390 isOrdered = false;
3391 switch (CC) {
3392 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3393 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003394 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3395 case FCmpInst::FCMP_UGT: return 1; // 001
3396 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3397 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003398 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3399 case FCmpInst::FCMP_UGE: return 3; // 011
3400 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3401 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003402 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3403 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003404 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3405 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003406 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003407 default:
3408 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003409 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003410 return 0;
3411 }
3412}
3413
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414/// getICmpValue - This is the complement of getICmpCode, which turns an
3415/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003416/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003417/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003418static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003419 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003420 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003421 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003422 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003423 case 1:
3424 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003425 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003426 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3428 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003429 case 3:
3430 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003432 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003433 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003434 case 4:
3435 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003436 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003437 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003438 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3439 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003440 case 6:
3441 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003442 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003443 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003444 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003445 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003446 }
3447}
3448
Evan Cheng8db90722008-10-14 17:15:11 +00003449/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3450/// opcode and two operands into either a FCmp instruction. isordered is passed
3451/// in to determine which kind of predicate to use in the new fcmp instruction.
3452static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003453 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003454 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003455 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003456 case 0:
3457 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003458 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003459 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003460 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003461 case 1:
3462 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003463 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003464 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003465 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003466 case 2:
3467 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003468 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003469 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003470 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003471 case 3:
3472 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003473 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003474 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003475 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003476 case 4:
3477 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003478 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003479 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003480 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003481 case 5:
3482 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003483 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003484 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003485 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003486 case 6:
3487 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003488 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003489 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003490 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003491 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003492 }
3493}
3494
Chris Lattnerb9553d62008-11-16 04:55:20 +00003495/// PredicatesFoldable - Return true if both predicates match sign or if at
3496/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003497static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3498 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003499 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3500 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501}
3502
3503namespace {
3504// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3505struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506 InstCombiner &IC;
3507 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003508 ICmpInst::Predicate pred;
3509 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3510 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3511 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003512 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003513 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3514 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003515 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3516 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003517 return false;
3518 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003519 Instruction *apply(Instruction &Log) const {
3520 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3521 if (ICI->getOperand(0) != LHS) {
3522 assert(ICI->getOperand(1) == LHS);
3523 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003524 }
3525
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003526 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003527 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003528 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003529 unsigned Code;
3530 switch (Log.getOpcode()) {
3531 case Instruction::And: Code = LHSCode & RHSCode; break;
3532 case Instruction::Or: Code = LHSCode | RHSCode; break;
3533 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003534 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003535 }
3536
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003537 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3538 ICmpInst::isSignedPredicate(ICI->getPredicate());
3539
Owen Andersond672ecb2009-07-03 00:17:18 +00003540 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003541 if (Instruction *I = dyn_cast<Instruction>(RV))
3542 return I;
3543 // Otherwise, it's a constant boolean value...
3544 return IC.ReplaceInstUsesWith(Log, RV);
3545 }
3546};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003547} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003548
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3550// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003551// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003552Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003553 ConstantInt *OpRHS,
3554 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 BinaryOperator &TheAnd) {
3556 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003557 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003558 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003559 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003560
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 switch (Op->getOpcode()) {
3562 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003563 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003565 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003566 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003567 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003568 }
3569 break;
3570 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003571 if (Together == AndRHS) // (X | C) & C --> C
3572 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003573
Chris Lattner6e7ba452005-01-01 16:22:27 +00003574 if (Op->hasOneUse() && Together != OpRHS) {
3575 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003576 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003577 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003578 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003579 }
3580 break;
3581 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003582 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003583 // Adding a one to a single bit bit-field should be turned into an XOR
3584 // of the bit. First thing to check is to see if this AND is with a
3585 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003586 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003587
3588 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003589 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003590 // Ok, at this point, we know that we are masking the result of the
3591 // ADD down to exactly one bit. If the constant we are adding has
3592 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003593 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003594
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003595 // Check to see if any bits below the one bit set in AndRHSV are set.
3596 if ((AddRHS & (AndRHSV-1)) == 0) {
3597 // If not, the only thing that can effect the output of the AND is
3598 // the bit specified by AndRHSV. If that bit is set, the effect of
3599 // the XOR is to toggle the bit. If it is clear, then the ADD has
3600 // no effect.
3601 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3602 TheAnd.setOperand(0, X);
3603 return &TheAnd;
3604 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003605 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003606 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003607 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003608 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003609 }
3610 }
3611 }
3612 }
3613 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003614
3615 case Instruction::Shl: {
3616 // We know that the AND will not produce any of the bits shifted in, so if
3617 // the anded constant includes them, clear them now!
3618 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003619 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003620 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003621 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003622 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003623
Zhou Sheng290bec52007-03-29 08:15:12 +00003624 if (CI->getValue() == ShlMask) {
3625 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003626 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3627 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003628 TheAnd.setOperand(1, CI);
3629 return &TheAnd;
3630 }
3631 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003632 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003633 case Instruction::LShr:
3634 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003635 // We know that the AND will not produce any of the bits shifted in, so if
3636 // the anded constant includes them, clear them now! This only applies to
3637 // unsigned shifts, because a signed shr may bring in set bits!
3638 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003639 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003640 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003641 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003642 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003643
Zhou Sheng290bec52007-03-29 08:15:12 +00003644 if (CI->getValue() == ShrMask) {
3645 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003646 return ReplaceInstUsesWith(TheAnd, Op);
3647 } else if (CI != AndRHS) {
3648 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3649 return &TheAnd;
3650 }
3651 break;
3652 }
3653 case Instruction::AShr:
3654 // Signed shr.
3655 // See if this is shifting in some sign extension, then masking it out
3656 // with an and.
3657 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003658 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003659 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003660 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003661 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003662 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003663 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003664 // Make the argument unsigned.
3665 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003666 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003667 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003668 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003669 }
3670 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003671 }
3672 return 0;
3673}
3674
Chris Lattner8b170942002-08-09 23:47:40 +00003675
Chris Lattnera96879a2004-09-29 17:40:11 +00003676/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3677/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3679/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003680/// insert new instructions.
3681Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 bool isSigned, bool Inside,
3683 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003684 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003685 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003686 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687
Chris Lattnera96879a2004-09-29 17:40:11 +00003688 if (Inside) {
3689 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003690 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003691
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003693 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003694 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003696 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003697 }
3698
3699 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003700 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003701 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003702 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003703 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003704 }
3705
3706 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003707 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003708
Reid Spencere4e40032007-03-21 23:19:50 +00003709 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003710 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003711 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003712 ICmpInst::Predicate pred = (isSigned ?
3713 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003714 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003715 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003716
Reid Spencere4e40032007-03-21 23:19:50 +00003717 // Emit V-Lo >u Hi-1-Lo
3718 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003719 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003720 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003721 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003722 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003723}
3724
Chris Lattner7203e152005-09-18 07:22:02 +00003725// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3726// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3727// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3728// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003729static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003730 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003731 uint32_t BitWidth = Val->getType()->getBitWidth();
3732 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003733
3734 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003735 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003736 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003737 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003738 return true;
3739}
3740
Chris Lattner7203e152005-09-18 07:22:02 +00003741/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3742/// where isSub determines whether the operator is a sub. If we can fold one of
3743/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003744///
3745/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3746/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3747/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3748///
3749/// return (A +/- B).
3750///
3751Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003752 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003753 Instruction &I) {
3754 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3755 if (!LHSI || LHSI->getNumOperands() != 2 ||
3756 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3757
3758 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3759
3760 switch (LHSI->getOpcode()) {
3761 default: return 0;
3762 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003763 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003764 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003765 if ((Mask->getValue().countLeadingZeros() +
3766 Mask->getValue().countPopulation()) ==
3767 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003768 break;
3769
3770 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3771 // part, we don't need any explicit masks to take them out of A. If that
3772 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003773 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003774 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003775 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003776 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003777 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003778 break;
3779 }
3780 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003781 return 0;
3782 case Instruction::Or:
3783 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003784 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003785 if ((Mask->getValue().countLeadingZeros() +
3786 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003787 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003788 break;
3789 return 0;
3790 }
3791
Chris Lattnerc8e77562005-09-18 04:24:45 +00003792 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003793 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3794 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003795}
3796
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003797/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3798Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3799 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003800 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003801 ConstantInt *LHSCst, *RHSCst;
3802 ICmpInst::Predicate LHSCC, RHSCC;
3803
Chris Lattnerea065fb2008-11-16 05:10:52 +00003804 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003805 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003806 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003807 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003808 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003809 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003810
3811 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3812 // where C is a power of 2
3813 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3814 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003815 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003816 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003817 }
3818
3819 // From here on, we only handle:
3820 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3821 if (Val != Val2) return 0;
3822
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003823 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3824 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3825 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3826 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3827 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3828 return 0;
3829
3830 // We can't fold (ugt x, C) & (sgt x, C2).
3831 if (!PredicatesFoldable(LHSCC, RHSCC))
3832 return 0;
3833
3834 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003835 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836 if (ICmpInst::isSignedPredicate(LHSCC) ||
3837 (ICmpInst::isEquality(LHSCC) &&
3838 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003839 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003841 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3842
3843 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 std::swap(LHS, RHS);
3845 std::swap(LHSCst, RHSCst);
3846 std::swap(LHSCC, RHSCC);
3847 }
3848
3849 // At this point, we know we have have two icmp instructions
3850 // comparing a value against two constants and and'ing the result
3851 // together. Because of the above check, we know that we only have
3852 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3853 // (from the FoldICmpLogical check above), that the two constants
3854 // are not equal and that the larger constant is on the RHS
3855 assert(LHSCst != RHSCst && "Compares not folded above?");
3856
3857 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003858 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_EQ:
3860 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003861 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3863 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3864 case ICmpInst::ICMP_SGT: // (X == 13 & X > 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_NE: // (X == 13 & X != 15) -> X == 13
3867 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3868 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3869 return ReplaceInstUsesWith(I, LHS);
3870 }
3871 case ICmpInst::ICMP_NE:
3872 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003873 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003875 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003876 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 break; // (X != 13 & X u< 15) -> no change
3878 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003879 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003880 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 break; // (X != 13 & X s< 15) -> no change
3882 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3883 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3884 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3885 return ReplaceInstUsesWith(I, RHS);
3886 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003887 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003888 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003889 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003890 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003891 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003892 }
3893 break; // (X != 13 & X != 15) -> no change
3894 }
3895 break;
3896 case ICmpInst::ICMP_ULT:
3897 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003898 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003899 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3900 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003901 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3903 break;
3904 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3905 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3906 return ReplaceInstUsesWith(I, LHS);
3907 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3908 break;
3909 }
3910 break;
3911 case ICmpInst::ICMP_SLT:
3912 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003913 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3915 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003916 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003917 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3920 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3921 return ReplaceInstUsesWith(I, LHS);
3922 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3923 break;
3924 }
3925 break;
3926 case ICmpInst::ICMP_UGT:
3927 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003928 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003929 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3930 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3931 return ReplaceInstUsesWith(I, RHS);
3932 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3933 break;
3934 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003935 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003936 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003937 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003938 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003939 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003940 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003941 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3942 break;
3943 }
3944 break;
3945 case ICmpInst::ICMP_SGT:
3946 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003947 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003948 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3949 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3950 return ReplaceInstUsesWith(I, RHS);
3951 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3952 break;
3953 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003954 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003955 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003956 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003957 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003958 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003959 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003960 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3961 break;
3962 }
3963 break;
3964 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003965
3966 return 0;
3967}
3968
Chris Lattner42d1be02009-07-23 05:14:02 +00003969Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3970 FCmpInst *RHS) {
3971
3972 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3973 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3974 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3975 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3976 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3977 // If either of the constants are nans, then the whole thing returns
3978 // false.
3979 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003980 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003981 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003982 LHS->getOperand(0), RHS->getOperand(0));
3983 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003984
3985 // Handle vector zeros. This occurs because the canonical form of
3986 // "fcmp ord x,x" is "fcmp ord x, 0".
3987 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3988 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003989 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003990 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003991 return 0;
3992 }
3993
3994 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3995 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3996 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3997
3998
3999 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4000 // Swap RHS operands to match LHS.
4001 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4002 std::swap(Op1LHS, Op1RHS);
4003 }
4004
4005 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4006 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4007 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004008 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004009
4010 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004011 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004012 if (Op0CC == FCmpInst::FCMP_TRUE)
4013 return ReplaceInstUsesWith(I, RHS);
4014 if (Op1CC == FCmpInst::FCMP_TRUE)
4015 return ReplaceInstUsesWith(I, LHS);
4016
4017 bool Op0Ordered;
4018 bool Op1Ordered;
4019 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4020 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4021 if (Op1Pred == 0) {
4022 std::swap(LHS, RHS);
4023 std::swap(Op0Pred, Op1Pred);
4024 std::swap(Op0Ordered, Op1Ordered);
4025 }
4026 if (Op0Pred == 0) {
4027 // uno && ueq -> uno && (uno || eq) -> ueq
4028 // ord && olt -> ord && (ord && lt) -> olt
4029 if (Op0Ordered == Op1Ordered)
4030 return ReplaceInstUsesWith(I, RHS);
4031
4032 // uno && oeq -> uno && (ord && eq) -> false
4033 // uno && ord -> false
4034 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004035 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004036 // ord && ueq -> ord && (uno || eq) -> oeq
4037 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4038 Op0LHS, Op0RHS, Context));
4039 }
4040 }
4041
4042 return 0;
4043}
4044
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004045
Chris Lattner7e708292002-06-25 16:13:24 +00004046Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004047 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004048 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004049
Chris Lattnere87597f2004-10-16 18:11:37 +00004050 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004051 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004052
Chris Lattner6e7ba452005-01-01 16:22:27 +00004053 // and X, X = X
4054 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004055 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004056
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004057 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004058 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004059 if (SimplifyDemandedInstructionBits(I))
4060 return &I;
4061 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004062 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004063 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004064 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004065 } else if (isa<ConstantAggregateZero>(Op1)) {
4066 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004067 }
4068 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004069
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004070 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004071 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004072 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004073
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004074 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004075 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004076 Value *Op0LHS = Op0I->getOperand(0);
4077 Value *Op0RHS = Op0I->getOperand(1);
4078 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004079 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004080 case Instruction::Xor:
4081 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004082 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004083 if (!Op0I->hasOneUse()) break;
4084
4085 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4086 // Not masking anything out for the LHS, move to RHS.
4087 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4088 Op0RHS->getName()+".masked");
4089 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4090 }
4091 if (!isa<Constant>(Op0RHS) &&
4092 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4093 // Not masking anything out for the RHS, move to LHS.
4094 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4095 Op0LHS->getName()+".masked");
4096 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004097 }
4098
Chris Lattner6e7ba452005-01-01 16:22:27 +00004099 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004100 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004101 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4102 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4103 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4104 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004105 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004106 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004107 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004108 break;
4109
4110 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004111 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4112 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4113 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4114 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004115 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004116
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004117 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4118 // has 1's for all bits that the subtraction with A might affect.
4119 if (Op0I->hasOneUse()) {
4120 uint32_t BitWidth = AndRHSMask.getBitWidth();
4121 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4122 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4123
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004124 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004125 if (!(A && A->isZero()) && // avoid infinite recursion.
4126 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004127 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004128 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4129 }
4130 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004131 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004132
4133 case Instruction::Shl:
4134 case Instruction::LShr:
4135 // (1 << x) & 1 --> zext(x == 0)
4136 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004137 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004138 Value *NewICmp =
4139 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004140 return new ZExtInst(NewICmp, I.getType());
4141 }
4142 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004143 }
4144
Chris Lattner58403262003-07-23 19:25:52 +00004145 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004146 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004147 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004148 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004149 // If this is an integer truncation or change from signed-to-unsigned, and
4150 // if the source is an and/or with immediate, transform it. This
4151 // frequently occurs for bitfield accesses.
4152 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004153 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004154 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004155 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004156 if (CastOp->getOpcode() == Instruction::And) {
4157 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004158 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4159 // This will fold the two constants together, which may allow
4160 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004161 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004162 CastOp->getOperand(0), I.getType(),
4163 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004164 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004165 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004166 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004167 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004168 } else if (CastOp->getOpcode() == Instruction::Or) {
4169 // Change: and (cast (or X, C1) to T), C2
4170 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004171 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004172 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004173 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004174 return ReplaceInstUsesWith(I, AndRHS);
4175 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004176 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004177 }
Chris Lattner06782f82003-07-23 19:36:21 +00004178 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004179
4180 // Try to fold constant and into select arguments.
4181 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004182 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004183 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004184 if (isa<PHINode>(Op0))
4185 if (Instruction *NV = FoldOpIntoPhi(I))
4186 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004187 }
4188
Dan Gohman186a6362009-08-12 16:04:34 +00004189 Value *Op0NotVal = dyn_castNotVal(Op0);
4190 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004191
Chris Lattner5b62aa72004-06-18 06:07:51 +00004192 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004193 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004194
Misha Brukmancb6267b2004-07-30 12:50:08 +00004195 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004196 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004197 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4198 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004199 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004200 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004201
4202 {
Chris Lattner003b6202007-06-15 05:58:24 +00004203 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004204 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004205 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4206 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004207
4208 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004209 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004210 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004211 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004212 }
4213 }
4214
Dan Gohman4ae51262009-08-12 16:23:25 +00004215 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004216 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4217 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004218
4219 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004220 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004221 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004222 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004223 }
4224 }
Chris Lattner64daab52006-04-01 08:03:55 +00004225
4226 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004227 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004228 if (A == Op1) { // (A^B)&A -> A&(A^B)
4229 I.swapOperands(); // Simplify below
4230 std::swap(Op0, Op1);
4231 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4232 cast<BinaryOperator>(Op0)->swapOperands();
4233 I.swapOperands(); // Simplify below
4234 std::swap(Op0, Op1);
4235 }
4236 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004237
Chris Lattner64daab52006-04-01 08:03:55 +00004238 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004239 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004240 if (B == Op0) { // B&(A^B) -> B&(B^A)
4241 cast<BinaryOperator>(Op1)->swapOperands();
4242 std::swap(A, B);
4243 }
Chris Lattner74381062009-08-30 07:44:24 +00004244 if (A == Op0) // A&(A^B) -> A & ~B
4245 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004246 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004247
4248 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004249 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4250 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004251 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004252 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4253 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004254 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004255 }
4256
Reid Spencere4d87aa2006-12-23 06:05:41 +00004257 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4258 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004259 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004260 return R;
4261
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004262 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4263 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4264 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004265 }
4266
Chris Lattner6fc205f2006-05-05 06:39:07 +00004267 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004268 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4269 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4270 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4271 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004272 if (SrcTy == Op1C->getOperand(0)->getType() &&
4273 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004274 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004275 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4276 I.getType(), TD) &&
4277 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4278 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004279 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4280 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004281 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004282 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004283 }
Chris Lattnere511b742006-11-14 07:46:50 +00004284
4285 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004286 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4287 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4288 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004289 SI0->getOperand(1) == SI1->getOperand(1) &&
4290 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004291 Value *NewOp =
4292 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4293 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004294 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004295 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004296 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004297 }
4298
Evan Cheng8db90722008-10-14 17:15:11 +00004299 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004300 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004301 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4302 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4303 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004304 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004305
Chris Lattner7e708292002-06-25 16:13:24 +00004306 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004307}
4308
Chris Lattner8c34cd22008-10-05 02:13:19 +00004309/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4310/// capable of providing pieces of a bswap. The subexpression provides pieces
4311/// of a bswap if it is proven that each of the non-zero bytes in the output of
4312/// the expression came from the corresponding "byte swapped" byte in some other
4313/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4314/// we know that the expression deposits the low byte of %X into the high byte
4315/// of the bswap result and that all other bytes are zero. This expression is
4316/// accepted, the high byte of ByteValues is set to X to indicate a correct
4317/// match.
4318///
4319/// This function returns true if the match was unsuccessful and false if so.
4320/// On entry to the function the "OverallLeftShift" is a signed integer value
4321/// indicating the number of bytes that the subexpression is later shifted. For
4322/// example, if the expression is later right shifted by 16 bits, the
4323/// OverallLeftShift value would be -2 on entry. This is used to specify which
4324/// byte of ByteValues is actually being set.
4325///
4326/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4327/// byte is masked to zero by a user. For example, in (X & 255), X will be
4328/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4329/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4330/// always in the local (OverallLeftShift) coordinate space.
4331///
4332static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4333 SmallVector<Value*, 8> &ByteValues) {
4334 if (Instruction *I = dyn_cast<Instruction>(V)) {
4335 // If this is an or instruction, it may be an inner node of the bswap.
4336 if (I->getOpcode() == Instruction::Or) {
4337 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4338 ByteValues) ||
4339 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4340 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004341 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004342
4343 // If this is a logical shift by a constant multiple of 8, recurse with
4344 // OverallLeftShift and ByteMask adjusted.
4345 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4346 unsigned ShAmt =
4347 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4348 // Ensure the shift amount is defined and of a byte value.
4349 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4350 return true;
4351
4352 unsigned ByteShift = ShAmt >> 3;
4353 if (I->getOpcode() == Instruction::Shl) {
4354 // X << 2 -> collect(X, +2)
4355 OverallLeftShift += ByteShift;
4356 ByteMask >>= ByteShift;
4357 } else {
4358 // X >>u 2 -> collect(X, -2)
4359 OverallLeftShift -= ByteShift;
4360 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004361 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004362 }
4363
4364 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4365 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4366
4367 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4368 ByteValues);
4369 }
4370
4371 // If this is a logical 'and' with a mask that clears bytes, clear the
4372 // corresponding bytes in ByteMask.
4373 if (I->getOpcode() == Instruction::And &&
4374 isa<ConstantInt>(I->getOperand(1))) {
4375 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4376 unsigned NumBytes = ByteValues.size();
4377 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4378 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4379
4380 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4381 // If this byte is masked out by a later operation, we don't care what
4382 // the and mask is.
4383 if ((ByteMask & (1 << i)) == 0)
4384 continue;
4385
4386 // If the AndMask is all zeros for this byte, clear the bit.
4387 APInt MaskB = AndMask & Byte;
4388 if (MaskB == 0) {
4389 ByteMask &= ~(1U << i);
4390 continue;
4391 }
4392
4393 // If the AndMask is not all ones for this byte, it's not a bytezap.
4394 if (MaskB != Byte)
4395 return true;
4396
4397 // Otherwise, this byte is kept.
4398 }
4399
4400 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4401 ByteValues);
4402 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004403 }
4404
Chris Lattner8c34cd22008-10-05 02:13:19 +00004405 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4406 // the input value to the bswap. Some observations: 1) if more than one byte
4407 // is demanded from this input, then it could not be successfully assembled
4408 // into a byteswap. At least one of the two bytes would not be aligned with
4409 // their ultimate destination.
4410 if (!isPowerOf2_32(ByteMask)) return true;
4411 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004412
Chris Lattner8c34cd22008-10-05 02:13:19 +00004413 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4414 // is demanded, it needs to go into byte 0 of the result. This means that the
4415 // byte needs to be shifted until it lands in the right byte bucket. The
4416 // shift amount depends on the position: if the byte is coming from the high
4417 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4418 // low part, it must be shifted left.
4419 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4420 if (InputByteNo < ByteValues.size()/2) {
4421 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4422 return true;
4423 } else {
4424 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4425 return true;
4426 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427
4428 // If the destination byte value is already defined, the values are or'd
4429 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004430 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004432 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004433 return false;
4434}
4435
4436/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4437/// If so, insert the new bswap intrinsic and return it.
4438Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004439 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004440 if (!ITy || ITy->getBitWidth() % 16 ||
4441 // ByteMask only allows up to 32-byte values.
4442 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004443 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004444
4445 /// ByteValues - For each byte of the result, we keep track of which value
4446 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004447 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004448 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004449
4450 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004451 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4452 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004453 return 0;
4454
4455 // Check to see if all of the bytes come from the same value.
4456 Value *V = ByteValues[0];
4457 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4458
4459 // Check to make sure that all of the bytes come from the same value.
4460 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4461 if (ByteValues[i] != V)
4462 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004463 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004464 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004465 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004466 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004467}
4468
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004469/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4470/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4471/// we can simplify this expression to "cond ? C : D or B".
4472static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004473 Value *C, Value *D,
4474 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004475 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004476 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004477 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004478 return 0;
4479
Chris Lattnera6a474d2008-11-16 04:26:55 +00004480 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004481 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004482 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004483 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004484 return SelectInst::Create(Cond, C, B);
4485 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004486 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004487 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004488 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004489 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004490 return 0;
4491}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004492
Chris Lattner69d4ced2008-11-16 05:20:07 +00004493/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4494Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4495 ICmpInst *LHS, ICmpInst *RHS) {
4496 Value *Val, *Val2;
4497 ConstantInt *LHSCst, *RHSCst;
4498 ICmpInst::Predicate LHSCC, RHSCC;
4499
4500 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004501 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004502 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004503 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004504 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004505 return 0;
4506
4507 // From here on, we only handle:
4508 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4509 if (Val != Val2) return 0;
4510
4511 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4512 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4513 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4514 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4515 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4516 return 0;
4517
4518 // We can't fold (ugt x, C) | (sgt x, C2).
4519 if (!PredicatesFoldable(LHSCC, RHSCC))
4520 return 0;
4521
4522 // Ensure that the larger constant is on the RHS.
4523 bool ShouldSwap;
4524 if (ICmpInst::isSignedPredicate(LHSCC) ||
4525 (ICmpInst::isEquality(LHSCC) &&
4526 ICmpInst::isSignedPredicate(RHSCC)))
4527 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4528 else
4529 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4530
4531 if (ShouldSwap) {
4532 std::swap(LHS, RHS);
4533 std::swap(LHSCst, RHSCst);
4534 std::swap(LHSCC, RHSCC);
4535 }
4536
4537 // At this point, we know we have have two icmp instructions
4538 // comparing a value against two constants and or'ing the result
4539 // together. Because of the above check, we know that we only have
4540 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4541 // FoldICmpLogical check above), that the two constants are not
4542 // equal.
4543 assert(LHSCst != RHSCst && "Compares not folded above?");
4544
4545 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004546 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004547 case ICmpInst::ICMP_EQ:
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:
Dan Gohman186a6362009-08-12 16:04:34 +00004551 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004552 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004553 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004554 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004555 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004556 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004557 }
4558 break; // (X == 13 | X == 15) -> no change
4559 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4560 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4561 break;
4562 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4563 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4564 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4565 return ReplaceInstUsesWith(I, RHS);
4566 }
4567 break;
4568 case ICmpInst::ICMP_NE:
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 != 13 | X == 15) -> X != 13
4572 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4573 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4574 return ReplaceInstUsesWith(I, LHS);
4575 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4576 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4577 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004578 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004579 }
4580 break;
4581 case ICmpInst::ICMP_ULT:
4582 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004583 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004584 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4585 break;
4586 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4587 // If RHSCst is [us]MAXINT, it is always false. Not handling
4588 // this can cause overflow.
4589 if (RHSCst->isMaxValue(false))
4590 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004591 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004592 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004593 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4594 break;
4595 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4596 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4597 return ReplaceInstUsesWith(I, RHS);
4598 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4599 break;
4600 }
4601 break;
4602 case ICmpInst::ICMP_SLT:
4603 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004604 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004605 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4606 break;
4607 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4608 // If RHSCst is [us]MAXINT, it is always false. Not handling
4609 // this can cause overflow.
4610 if (RHSCst->isMaxValue(true))
4611 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004612 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004613 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004614 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4615 break;
4616 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4617 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4618 return ReplaceInstUsesWith(I, RHS);
4619 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4620 break;
4621 }
4622 break;
4623 case ICmpInst::ICMP_UGT:
4624 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004625 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004626 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4627 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4628 return ReplaceInstUsesWith(I, LHS);
4629 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4632 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004633 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004634 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4635 break;
4636 }
4637 break;
4638 case ICmpInst::ICMP_SGT:
4639 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004640 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004641 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4642 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4643 return ReplaceInstUsesWith(I, LHS);
4644 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4645 break;
4646 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4647 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004649 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4650 break;
4651 }
4652 break;
4653 }
4654 return 0;
4655}
4656
Chris Lattner5414cc52009-07-23 05:46:22 +00004657Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4658 FCmpInst *RHS) {
4659 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4660 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4661 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4662 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4663 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4664 // If either of the constants are nans, then the whole thing returns
4665 // true.
4666 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004667 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004668
4669 // Otherwise, no need to compare the two constants, compare the
4670 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004671 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004672 LHS->getOperand(0), RHS->getOperand(0));
4673 }
4674
4675 // Handle vector zeros. This occurs because the canonical form of
4676 // "fcmp uno x,x" is "fcmp uno x, 0".
4677 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4678 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004679 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004680 LHS->getOperand(0), RHS->getOperand(0));
4681
4682 return 0;
4683 }
4684
4685 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4686 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4687 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4688
4689 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4690 // Swap RHS operands to match LHS.
4691 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4692 std::swap(Op1LHS, Op1RHS);
4693 }
4694 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4695 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4696 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004697 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004698 Op0LHS, Op0RHS);
4699 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004700 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004701 if (Op0CC == FCmpInst::FCMP_FALSE)
4702 return ReplaceInstUsesWith(I, RHS);
4703 if (Op1CC == FCmpInst::FCMP_FALSE)
4704 return ReplaceInstUsesWith(I, LHS);
4705 bool Op0Ordered;
4706 bool Op1Ordered;
4707 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4708 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4709 if (Op0Ordered == Op1Ordered) {
4710 // If both are ordered or unordered, return a new fcmp with
4711 // or'ed predicates.
4712 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4713 Op0LHS, Op0RHS, Context);
4714 if (Instruction *I = dyn_cast<Instruction>(RV))
4715 return I;
4716 // Otherwise, it's a constant boolean value...
4717 return ReplaceInstUsesWith(I, RV);
4718 }
4719 }
4720 return 0;
4721}
4722
Bill Wendlinga698a472008-12-01 08:23:25 +00004723/// FoldOrWithConstants - This helper function folds:
4724///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004725/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004726///
4727/// into:
4728///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004729/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004730///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004731/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004732Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004733 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004734 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4735 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004736
Bill Wendling286a0542008-12-02 06:24:20 +00004737 Value *V1 = 0;
4738 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004739 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004740
Bill Wendling29976b92008-12-02 06:18:11 +00004741 APInt Xor = CI1->getValue() ^ CI2->getValue();
4742 if (!Xor.isAllOnesValue()) return 0;
4743
Bill Wendling286a0542008-12-02 06:24:20 +00004744 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004745 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004746 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004747 }
4748
4749 return 0;
4750}
4751
Chris Lattner7e708292002-06-25 16:13:24 +00004752Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004753 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004754 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004755
Chris Lattner42593e62007-03-24 23:56:43 +00004756 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004757 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004758
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004759 // or X, X = X
4760 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004761 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004762
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004763 // See if we can simplify any instructions used by the instruction whose sole
4764 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004765 if (SimplifyDemandedInstructionBits(I))
4766 return &I;
4767 if (isa<VectorType>(I.getType())) {
4768 if (isa<ConstantAggregateZero>(Op1)) {
4769 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4770 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4771 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4772 return ReplaceInstUsesWith(I, I.getOperand(1));
4773 }
Chris Lattner42593e62007-03-24 23:56:43 +00004774 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004775
Chris Lattner3f5b8772002-05-06 16:14:14 +00004776 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004777 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004778 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004779 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004780 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004781 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004782 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004783 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004784 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004785 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004786 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004787
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004788 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004789 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004790 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004791 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004792 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004793 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004794 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004795 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004796
4797 // Try to fold constant and into select arguments.
4798 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004799 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004800 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004801 if (isa<PHINode>(Op0))
4802 if (Instruction *NV = FoldOpIntoPhi(I))
4803 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004804 }
4805
Chris Lattner4f637d42006-01-06 17:59:59 +00004806 Value *A = 0, *B = 0;
4807 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004808
Dan Gohman4ae51262009-08-12 16:23:25 +00004809 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004810 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4811 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004812 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004813 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4814 return ReplaceInstUsesWith(I, Op0);
4815
Chris Lattner6423d4c2006-07-10 20:25:24 +00004816 // (A | B) | C and A | (B | C) -> bswap if possible.
4817 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004818 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4819 match(Op1, m_Or(m_Value(), m_Value())) ||
4820 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4821 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004822 if (Instruction *BSwap = MatchBSwap(I))
4823 return BSwap;
4824 }
4825
Chris Lattner6e4c6492005-05-09 04:58:36 +00004826 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004827 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004828 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004829 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004830 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004831 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004832 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004833 }
4834
4835 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004836 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004837 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004838 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004839 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004840 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004841 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004842 }
4843
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004844 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004845 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004846 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4847 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004848 Value *V1 = 0, *V2 = 0, *V3 = 0;
4849 C1 = dyn_cast<ConstantInt>(C);
4850 C2 = dyn_cast<ConstantInt>(D);
4851 if (C1 && C2) { // (A & C1)|(B & C2)
4852 // If we have: ((V + N) & C1) | (V & C2)
4853 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4854 // replace with V+N.
4855 if (C1->getValue() == ~C2->getValue()) {
4856 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004857 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004858 // Add commutes, try both ways.
4859 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4860 return ReplaceInstUsesWith(I, A);
4861 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4862 return ReplaceInstUsesWith(I, A);
4863 }
4864 // Or commutes, try both ways.
4865 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004866 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004867 // Add commutes, try both ways.
4868 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4869 return ReplaceInstUsesWith(I, B);
4870 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4871 return ReplaceInstUsesWith(I, B);
4872 }
4873 }
Chris Lattner044e5332007-04-08 08:01:49 +00004874 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004875 }
4876
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004877 // Check to see if we have any common things being and'ed. If so, find the
4878 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004879 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4880 if (A == B) // (A & C)|(A & D) == A & (C|D)
4881 V1 = A, V2 = C, V3 = D;
4882 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4883 V1 = A, V2 = B, V3 = C;
4884 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4885 V1 = C, V2 = A, V3 = D;
4886 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4887 V1 = C, V2 = A, V3 = B;
4888
4889 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004890 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004891 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004892 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004893 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004894
Dan Gohman1975d032008-10-30 20:40:10 +00004895 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004896 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004897 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004898 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004899 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004900 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004901 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004902 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004903 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004904
Bill Wendlingb01865c2008-11-30 13:52:49 +00004905 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004906 if ((match(C, m_Not(m_Specific(D))) &&
4907 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004908 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004909 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004910 if ((match(A, m_Not(m_Specific(D))) &&
4911 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004912 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004913 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004914 if ((match(C, m_Not(m_Specific(B))) &&
4915 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004916 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004917 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004918 if ((match(A, m_Not(m_Specific(B))) &&
4919 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004920 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004921 }
Chris Lattnere511b742006-11-14 07:46:50 +00004922
4923 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004924 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4925 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4926 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004927 SI0->getOperand(1) == SI1->getOperand(1) &&
4928 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004929 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4930 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004931 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004932 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004933 }
4934 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004935
Bill Wendlingb3833d12008-12-01 01:07:11 +00004936 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004937 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4938 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004939 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004940 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004941 }
4942 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004943 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4944 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004945 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004946 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004947 }
4948
Dan Gohman4ae51262009-08-12 16:23:25 +00004949 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004950 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004951 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004952 } else {
4953 A = 0;
4954 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004955 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004956 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004957 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004958 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004959
Misha Brukmancb6267b2004-07-30 12:50:08 +00004960 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004961 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004962 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004963 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004964 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004965 }
Chris Lattnera2881962003-02-18 19:28:33 +00004966
Reid Spencere4d87aa2006-12-23 06:05:41 +00004967 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4968 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004969 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004970 return R;
4971
Chris Lattner69d4ced2008-11-16 05:20:07 +00004972 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4973 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4974 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004975 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004976
4977 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004978 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004979 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004980 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004981 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4982 !isa<ICmpInst>(Op1C->getOperand(0))) {
4983 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004984 if (SrcTy == Op1C->getOperand(0)->getType() &&
4985 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004986 // Only do this if the casts both really cause code to be
4987 // generated.
4988 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4989 I.getType(), TD) &&
4990 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4991 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004992 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4993 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004994 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004995 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004996 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004997 }
Chris Lattner99c65742007-10-24 05:38:08 +00004998 }
4999
5000
5001 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5002 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005003 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5004 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5005 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005006 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005007
Chris Lattner7e708292002-06-25 16:13:24 +00005008 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005009}
5010
Dan Gohman844731a2008-05-13 00:00:25 +00005011namespace {
5012
Chris Lattnerc317d392004-02-16 01:20:27 +00005013// XorSelf - Implements: X ^ X --> 0
5014struct XorSelf {
5015 Value *RHS;
5016 XorSelf(Value *rhs) : RHS(rhs) {}
5017 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5018 Instruction *apply(BinaryOperator &Xor) const {
5019 return &Xor;
5020 }
5021};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005022
Dan Gohman844731a2008-05-13 00:00:25 +00005023}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005024
Chris Lattner7e708292002-06-25 16:13:24 +00005025Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005026 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005027 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005028
Evan Chengd34af782008-03-25 20:07:13 +00005029 if (isa<UndefValue>(Op1)) {
5030 if (isa<UndefValue>(Op0))
5031 // Handle undef ^ undef -> 0 special case. This is a common
5032 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005034 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005035 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005036
Chris Lattnerc317d392004-02-16 01:20:27 +00005037 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005038 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005039 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005040 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005041 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005042
5043 // See if we can simplify any instructions used by the instruction whose sole
5044 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005045 if (SimplifyDemandedInstructionBits(I))
5046 return &I;
5047 if (isa<VectorType>(I.getType()))
5048 if (isa<ConstantAggregateZero>(Op1))
5049 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005050
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005051 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005052 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005053 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5054 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5055 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5056 if (Op0I->getOpcode() == Instruction::And ||
5057 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005058 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5059 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005060 Value *NotY =
5061 Builder->CreateNot(Op0I->getOperand(1),
5062 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005063 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005064 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005065 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005066 }
5067 }
5068 }
5069 }
5070
5071
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005072 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005073 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005074 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005075 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005076 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005077 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005078
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005079 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005080 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005081 FCI->getOperand(0), FCI->getOperand(1));
5082 }
5083
Nick Lewycky517e1f52008-05-31 19:01:33 +00005084 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5085 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5086 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5087 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5088 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005089 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5090 (RHS == ConstantExpr::getCast(Opcode,
5091 ConstantInt::getTrue(*Context),
5092 Op0C->getDestTy()))) {
5093 CI->setPredicate(CI->getInversePredicate());
5094 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005095 }
5096 }
5097 }
5098 }
5099
Reid Spencere4d87aa2006-12-23 06:05:41 +00005100 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005101 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005102 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5103 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005104 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5105 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005106 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005107 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005108 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005109
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005110 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005111 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005112 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005113 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005114 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005115 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005116 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005117 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005118 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005119 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005120 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005121 Constant *C = ConstantInt::get(*Context,
5122 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005123 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005124
Chris Lattner7c4049c2004-01-12 19:35:11 +00005125 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005126 } else if (Op0I->getOpcode() == Instruction::Or) {
5127 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005128 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005129 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005130 // Anything in both C1 and C2 is known to be zero, remove it from
5131 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005132 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5133 NewRHS = ConstantExpr::getAnd(NewRHS,
5134 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005135 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005136 I.setOperand(0, Op0I->getOperand(0));
5137 I.setOperand(1, NewRHS);
5138 return &I;
5139 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005140 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005141 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005142 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005143
5144 // Try to fold constant and into select arguments.
5145 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005146 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005147 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005148 if (isa<PHINode>(Op0))
5149 if (Instruction *NV = FoldOpIntoPhi(I))
5150 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005151 }
5152
Dan Gohman186a6362009-08-12 16:04:34 +00005153 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005154 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005155 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005156
Dan Gohman186a6362009-08-12 16:04:34 +00005157 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005158 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005159 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005160
Chris Lattner318bf792007-03-18 22:51:34 +00005161
5162 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5163 if (Op1I) {
5164 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005165 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005166 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005167 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005168 I.swapOperands();
5169 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005170 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005171 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005172 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005173 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005174 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005175 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005176 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005177 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005178 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005180 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005181 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005182 std::swap(A, B);
5183 }
Chris Lattner318bf792007-03-18 22:51:34 +00005184 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005185 I.swapOperands(); // Simplified below.
5186 std::swap(Op0, Op1);
5187 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005188 }
Chris Lattner318bf792007-03-18 22:51:34 +00005189 }
5190
5191 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5192 if (Op0I) {
5193 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005194 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005195 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005196 if (A == Op1) // (B|A)^B == (A|B)^B
5197 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005198 if (B == Op1) // (A|B)^B == A & ~B
5199 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005200 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005201 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005202 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005203 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005204 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005205 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005206 if (A == Op1) // (A&B)^A -> (B&A)^A
5207 std::swap(A, B);
5208 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005209 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005210 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005211 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005212 }
Chris Lattner318bf792007-03-18 22:51:34 +00005213 }
5214
5215 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5216 if (Op0I && Op1I && Op0I->isShift() &&
5217 Op0I->getOpcode() == Op1I->getOpcode() &&
5218 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5219 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005220 Value *NewOp =
5221 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5222 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005223 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005224 Op1I->getOperand(1));
5225 }
5226
5227 if (Op0I && Op1I) {
5228 Value *A, *B, *C, *D;
5229 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005230 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5231 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005232 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005233 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005234 }
5235 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005236 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5237 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005238 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005239 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005240 }
5241
5242 // (A & B)^(C & D)
5243 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005244 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5245 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005246 // (X & Y)^(X & Y) -> (Y^Z) & X
5247 Value *X = 0, *Y = 0, *Z = 0;
5248 if (A == C)
5249 X = A, Y = B, Z = D;
5250 else if (A == D)
5251 X = A, Y = B, Z = C;
5252 else if (B == C)
5253 X = B, Y = A, Z = D;
5254 else if (B == D)
5255 X = B, Y = A, Z = C;
5256
5257 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005258 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005259 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005260 }
5261 }
5262 }
5263
Reid Spencere4d87aa2006-12-23 06:05:41 +00005264 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5265 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005266 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005267 return R;
5268
Chris Lattner6fc205f2006-05-05 06:39:07 +00005269 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005270 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005271 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005272 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5273 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005274 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005275 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005276 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5277 I.getType(), TD) &&
5278 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5279 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005280 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5281 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005282 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005283 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005284 }
Chris Lattner99c65742007-10-24 05:38:08 +00005285 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005286
Chris Lattner7e708292002-06-25 16:13:24 +00005287 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005288}
5289
Owen Andersond672ecb2009-07-03 00:17:18 +00005290static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005291 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005292 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005293}
Chris Lattnera96879a2004-09-29 17:40:11 +00005294
Dan Gohman6de29f82009-06-15 22:12:54 +00005295static bool HasAddOverflow(ConstantInt *Result,
5296 ConstantInt *In1, ConstantInt *In2,
5297 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005298 if (IsSigned)
5299 if (In2->getValue().isNegative())
5300 return Result->getValue().sgt(In1->getValue());
5301 else
5302 return Result->getValue().slt(In1->getValue());
5303 else
5304 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005305}
5306
Dan Gohman6de29f82009-06-15 22:12:54 +00005307/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005308/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005309static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005310 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005311 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005312 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005313
Dan Gohman6de29f82009-06-15 22:12:54 +00005314 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5315 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005316 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005317 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5318 ExtractElement(In1, Idx, Context),
5319 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005320 IsSigned))
5321 return true;
5322 }
5323 return false;
5324 }
5325
5326 return HasAddOverflow(cast<ConstantInt>(Result),
5327 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5328 IsSigned);
5329}
5330
5331static bool HasSubOverflow(ConstantInt *Result,
5332 ConstantInt *In1, ConstantInt *In2,
5333 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005334 if (IsSigned)
5335 if (In2->getValue().isNegative())
5336 return Result->getValue().slt(In1->getValue());
5337 else
5338 return Result->getValue().sgt(In1->getValue());
5339 else
5340 return Result->getValue().ugt(In1->getValue());
5341}
5342
Dan Gohman6de29f82009-06-15 22:12:54 +00005343/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5344/// overflowed for this type.
5345static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005346 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005347 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005348 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005349
5350 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5351 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005352 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005353 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5354 ExtractElement(In1, Idx, Context),
5355 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005356 IsSigned))
5357 return true;
5358 }
5359 return false;
5360 }
5361
5362 return HasSubOverflow(cast<ConstantInt>(Result),
5363 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5364 IsSigned);
5365}
5366
Chris Lattner574da9b2005-01-13 20:14:25 +00005367/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5368/// code necessary to compute the offset from the base pointer (without adding
5369/// in the base pointer). Return the result as a signed integer of intptr size.
5370static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005371 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005372 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005373 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005374 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005375
5376 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005377 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005378 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005379
Gabor Greif177dd3f2008-06-12 21:37:33 +00005380 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5381 ++i, ++GTI) {
5382 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005383 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005384 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5385 if (OpC->isZero()) continue;
5386
5387 // Handle a struct index, which adds its field offset to the pointer.
5388 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5389 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5390
Chris Lattner74381062009-08-30 07:44:24 +00005391 Result = IC.Builder->CreateAdd(Result,
5392 ConstantInt::get(IntPtrTy, Size),
5393 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005394 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005395 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005396
Owen Andersoneed707b2009-07-24 23:12:02 +00005397 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005398 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005399 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5400 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005401 // Emit an add instruction.
5402 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005403 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005404 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005405 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005406 if (Op->getType() != IntPtrTy)
5407 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005409 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005410 // We'll let instcombine(mul) convert this to a shl if possible.
5411 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005412 }
5413
5414 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005415 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005416 }
5417 return Result;
5418}
5419
Chris Lattner10c0d912008-04-22 02:53:33 +00005420
Dan Gohman8f080f02009-07-17 22:16:21 +00005421/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5422/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5423/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5424/// be complex, and scales are involved. The above expression would also be
5425/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5426/// This later form is less amenable to optimization though, and we are allowed
5427/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005428///
5429/// If we can't emit an optimized form for this expression, this returns null.
5430///
5431static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5432 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005433 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005434 gep_type_iterator GTI = gep_type_begin(GEP);
5435
5436 // Check to see if this gep only has a single variable index. If so, and if
5437 // any constant indices are a multiple of its scale, then we can compute this
5438 // in terms of the scale of the variable index. For example, if the GEP
5439 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5440 // because the expression will cross zero at the same point.
5441 unsigned i, e = GEP->getNumOperands();
5442 int64_t Offset = 0;
5443 for (i = 1; i != e; ++i, ++GTI) {
5444 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5445 // Compute the aggregate offset of constant indices.
5446 if (CI->isZero()) continue;
5447
5448 // Handle a struct index, which adds its field offset to the pointer.
5449 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5450 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5451 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005452 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005453 Offset += Size*CI->getSExtValue();
5454 }
5455 } else {
5456 // Found our variable index.
5457 break;
5458 }
5459 }
5460
5461 // If there are no variable indices, we must have a constant offset, just
5462 // evaluate it the general way.
5463 if (i == e) return 0;
5464
5465 Value *VariableIdx = GEP->getOperand(i);
5466 // Determine the scale factor of the variable element. For example, this is
5467 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005468 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005469
5470 // Verify that there are no other variable indices. If so, emit the hard way.
5471 for (++i, ++GTI; i != e; ++i, ++GTI) {
5472 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5473 if (!CI) return 0;
5474
5475 // Compute the aggregate offset of constant indices.
5476 if (CI->isZero()) continue;
5477
5478 // Handle a struct index, which adds its field offset to the pointer.
5479 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5480 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5481 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005482 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005483 Offset += Size*CI->getSExtValue();
5484 }
5485 }
5486
5487 // Okay, we know we have a single variable index, which must be a
5488 // pointer/array/vector index. If there is no offset, life is simple, return
5489 // the index.
5490 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5491 if (Offset == 0) {
5492 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5493 // we don't need to bother extending: the extension won't affect where the
5494 // computation crosses zero.
5495 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005496 VariableIdx = new TruncInst(VariableIdx,
5497 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005498 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005499 return VariableIdx;
5500 }
5501
5502 // Otherwise, there is an index. The computation we will do will be modulo
5503 // the pointer size, so get it.
5504 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5505
5506 Offset &= PtrSizeMask;
5507 VariableScale &= PtrSizeMask;
5508
5509 // To do this transformation, any constant index must be a multiple of the
5510 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5511 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5512 // multiple of the variable scale.
5513 int64_t NewOffs = Offset / (int64_t)VariableScale;
5514 if (Offset != NewOffs*(int64_t)VariableScale)
5515 return 0;
5516
5517 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005518 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005519 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005520 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005521 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005522 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005523 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005524 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005525}
5526
5527
Reid Spencere4d87aa2006-12-23 06:05:41 +00005528/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005529/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005530Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005531 ICmpInst::Predicate Cond,
5532 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005533 // Look through bitcasts.
5534 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5535 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005536
Chris Lattner574da9b2005-01-13 20:14:25 +00005537 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005538 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005539 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005540 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005541 // know pointers can't overflow since the gep is inbounds. See if we can
5542 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005543 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5544
5545 // If not, synthesize the offset the hard way.
5546 if (Offset == 0)
5547 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005548 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005549 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005550 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005551 // If the base pointers are different, but the indices are the same, just
5552 // compare the base pointer.
5553 if (PtrBase != GEPRHS->getOperand(0)) {
5554 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005555 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005556 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005557 if (IndicesTheSame)
5558 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5559 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5560 IndicesTheSame = false;
5561 break;
5562 }
5563
5564 // If all indices are the same, just compare the base pointers.
5565 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005566 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005567 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005568
5569 // Otherwise, the base pointers are different and the indices are
5570 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005571 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005572 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005573
Chris Lattnere9d782b2005-01-13 22:25:21 +00005574 // If one of the GEPs has all zero indices, recurse.
5575 bool AllZeros = true;
5576 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5577 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5578 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5579 AllZeros = false;
5580 break;
5581 }
5582 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5584 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005585
5586 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005587 AllZeros = true;
5588 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5589 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5590 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5591 AllZeros = false;
5592 break;
5593 }
5594 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005595 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005596
Chris Lattner4401c9c2005-01-14 00:20:05 +00005597 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5598 // If the GEPs only differ by one index, compare it.
5599 unsigned NumDifferences = 0; // Keep track of # differences.
5600 unsigned DiffOperand = 0; // The operand that differs.
5601 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5602 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005603 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5604 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005605 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005606 NumDifferences = 2;
5607 break;
5608 } else {
5609 if (NumDifferences++) break;
5610 DiffOperand = i;
5611 }
5612 }
5613
5614 if (NumDifferences == 0) // SAME GEP?
5615 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005616 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005617 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005618
Chris Lattner4401c9c2005-01-14 00:20:05 +00005619 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005620 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5621 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005622 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005623 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005624 }
5625 }
5626
Reid Spencere4d87aa2006-12-23 06:05:41 +00005627 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005628 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005629 if (TD &&
5630 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005631 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5632 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5633 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5634 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005635 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005636 }
5637 }
5638 return 0;
5639}
5640
Chris Lattnera5406232008-05-19 20:18:56 +00005641/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5642///
5643Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5644 Instruction *LHSI,
5645 Constant *RHSC) {
5646 if (!isa<ConstantFP>(RHSC)) return 0;
5647 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5648
5649 // Get the width of the mantissa. We don't want to hack on conversions that
5650 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005651 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005652 if (MantissaWidth == -1) return 0; // Unknown.
5653
5654 // Check to see that the input is converted from an integer type that is small
5655 // enough that preserves all bits. TODO: check here for "known" sign bits.
5656 // 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 +00005657 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005658
5659 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005660 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5661 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005662 ++InputSize;
5663
5664 // If the conversion would lose info, don't hack on this.
5665 if ((int)InputSize > MantissaWidth)
5666 return 0;
5667
5668 // Otherwise, we can potentially simplify the comparison. We know that it
5669 // will always come through as an integer value and we know the constant is
5670 // not a NAN (it would have been previously simplified).
5671 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5672
5673 ICmpInst::Predicate Pred;
5674 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005675 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005676 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005677 case FCmpInst::FCMP_OEQ:
5678 Pred = ICmpInst::ICMP_EQ;
5679 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005680 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005681 case FCmpInst::FCMP_OGT:
5682 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5683 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005684 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005685 case FCmpInst::FCMP_OGE:
5686 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5687 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005688 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005689 case FCmpInst::FCMP_OLT:
5690 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5691 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005692 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005693 case FCmpInst::FCMP_OLE:
5694 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5695 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005696 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005697 case FCmpInst::FCMP_ONE:
5698 Pred = ICmpInst::ICMP_NE;
5699 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005700 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005701 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005702 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005703 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005704 }
5705
5706 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5707
5708 // Now we know that the APFloat is a normal number, zero or inf.
5709
Chris Lattner85162782008-05-20 03:50:52 +00005710 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005711 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005712 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005713
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005714 if (!LHSUnsigned) {
5715 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5716 // and large values.
5717 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5718 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5719 APFloat::rmNearestTiesToEven);
5720 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5721 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5722 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005723 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5724 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005725 }
5726 } else {
5727 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5728 // +INF and large values.
5729 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5730 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5731 APFloat::rmNearestTiesToEven);
5732 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5733 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5734 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005735 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5736 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005737 }
Chris Lattnera5406232008-05-19 20:18:56 +00005738 }
5739
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005740 if (!LHSUnsigned) {
5741 // See if the RHS value is < SignedMin.
5742 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5743 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5744 APFloat::rmNearestTiesToEven);
5745 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5746 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5747 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005748 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5749 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005750 }
Chris Lattnera5406232008-05-19 20:18:56 +00005751 }
5752
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005753 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5754 // [0, UMAX], but it may still be fractional. See if it is fractional by
5755 // casting the FP value to the integer value and back, checking for equality.
5756 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005757 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005758 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5759 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005760 if (!RHS.isZero()) {
5761 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005762 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5763 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005764 if (!Equal) {
5765 // If we had a comparison against a fractional value, we have to adjust
5766 // the compare predicate and sometimes the value. RHSC is rounded towards
5767 // zero at this point.
5768 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005769 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005770 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005771 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005772 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005773 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005774 case ICmpInst::ICMP_ULE:
5775 // (float)int <= 4.4 --> int <= 4
5776 // (float)int <= -4.4 --> false
5777 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005778 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005779 break;
5780 case ICmpInst::ICMP_SLE:
5781 // (float)int <= 4.4 --> int <= 4
5782 // (float)int <= -4.4 --> int < -4
5783 if (RHS.isNegative())
5784 Pred = ICmpInst::ICMP_SLT;
5785 break;
5786 case ICmpInst::ICMP_ULT:
5787 // (float)int < -4.4 --> false
5788 // (float)int < 4.4 --> int <= 4
5789 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005790 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005791 Pred = ICmpInst::ICMP_ULE;
5792 break;
5793 case ICmpInst::ICMP_SLT:
5794 // (float)int < -4.4 --> int < -4
5795 // (float)int < 4.4 --> int <= 4
5796 if (!RHS.isNegative())
5797 Pred = ICmpInst::ICMP_SLE;
5798 break;
5799 case ICmpInst::ICMP_UGT:
5800 // (float)int > 4.4 --> int > 4
5801 // (float)int > -4.4 --> true
5802 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005803 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005804 break;
5805 case ICmpInst::ICMP_SGT:
5806 // (float)int > 4.4 --> int > 4
5807 // (float)int > -4.4 --> int >= -4
5808 if (RHS.isNegative())
5809 Pred = ICmpInst::ICMP_SGE;
5810 break;
5811 case ICmpInst::ICMP_UGE:
5812 // (float)int >= -4.4 --> true
5813 // (float)int >= 4.4 --> int > 4
5814 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005815 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005816 Pred = ICmpInst::ICMP_UGT;
5817 break;
5818 case ICmpInst::ICMP_SGE:
5819 // (float)int >= -4.4 --> int >= -4
5820 // (float)int >= 4.4 --> int > 4
5821 if (!RHS.isNegative())
5822 Pred = ICmpInst::ICMP_SGT;
5823 break;
5824 }
Chris Lattnera5406232008-05-19 20:18:56 +00005825 }
5826 }
5827
5828 // Lower this FP comparison into an appropriate integer version of the
5829 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005830 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005831}
5832
Reid Spencere4d87aa2006-12-23 06:05:41 +00005833Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5834 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005835 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005836
Chris Lattner58e97462007-01-14 19:42:17 +00005837 // Fold trivial predicates.
5838 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005839 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005840 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005841 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005842
5843 // Simplify 'fcmp pred X, X'
5844 if (Op0 == Op1) {
5845 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005846 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005847 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5848 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5849 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005850 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005851 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5852 case FCmpInst::FCMP_OLT: // True if ordered and less than
5853 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005854 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005855
5856 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5857 case FCmpInst::FCMP_ULT: // True if unordered or less than
5858 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5859 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5860 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5861 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005862 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005863 return &I;
5864
5865 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5866 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5867 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5868 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5869 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5870 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005871 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005872 return &I;
5873 }
5874 }
5875
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005877 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005878
Reid Spencere4d87aa2006-12-23 06:05:41 +00005879 // Handle fcmp with constant RHS
5880 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005881 // If the constant is a nan, see if we can fold the comparison based on it.
5882 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5883 if (CFP->getValueAPF().isNaN()) {
5884 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005885 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005886 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5887 "Comparison must be either ordered or unordered!");
5888 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005889 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005890 }
5891 }
5892
Reid Spencere4d87aa2006-12-23 06:05:41 +00005893 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5894 switch (LHSI->getOpcode()) {
5895 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005896 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5897 // block. If in the same block, we're encouraging jump threading. If
5898 // not, we are just pessimizing the code by making an i1 phi.
5899 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005900 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005901 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005902 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005903 case Instruction::SIToFP:
5904 case Instruction::UIToFP:
5905 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5906 return NV;
5907 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005908 case Instruction::Select:
5909 // If either operand of the select is a constant, we can fold the
5910 // comparison into the select arms, which will cause one to be
5911 // constant folded and the select turned into a bitwise or.
5912 Value *Op1 = 0, *Op2 = 0;
5913 if (LHSI->hasOneUse()) {
5914 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5915 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005916 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005918 Op2 = Builder->CreateFCmp(I.getPredicate(),
5919 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005920 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5921 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005922 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005923 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005924 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5925 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005926 }
5927 }
5928
5929 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005930 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931 break;
5932 }
5933 }
5934
5935 return Changed ? &I : 0;
5936}
5937
5938Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5939 bool Changed = SimplifyCompare(I);
5940 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5941 const Type *Ty = Op0->getType();
5942
5943 // icmp X, X
5944 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005945 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005946 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005947
5948 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005949 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005950
Reid Spencere4d87aa2006-12-23 06:05:41 +00005951 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005952 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00005953 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005954 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00005955 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005956 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005957 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005958 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005959
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005961 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005963 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005964 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005965 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005966 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005967 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005968 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005969 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005970
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005972 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005973 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005974 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005975 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005976 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005977 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005978 case ICmpInst::ICMP_SGT:
5979 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005980 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005981 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005982 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005983 return BinaryOperator::CreateAnd(Not, Op0);
5984 }
5985 case ICmpInst::ICMP_UGE:
5986 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5987 // FALL THROUGH
5988 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005989 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005990 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005991 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005992 case ICmpInst::ICMP_SGE:
5993 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5994 // FALL THROUGH
5995 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005996 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005997 return BinaryOperator::CreateOr(Not, Op0);
5998 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005999 }
Chris Lattner8b170942002-08-09 23:47:40 +00006000 }
6001
Dan Gohman1c8491e2009-04-25 17:12:48 +00006002 unsigned BitWidth = 0;
6003 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006004 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6005 else if (Ty->isIntOrIntVector())
6006 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006007
6008 bool isSignBit = false;
6009
Dan Gohman81b28ce2008-09-16 18:46:06 +00006010 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006011 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006012 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006013
Chris Lattnerb6566012008-01-05 01:18:20 +00006014 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6015 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006016 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006017 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006018 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006019 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006020
Dan Gohman81b28ce2008-09-16 18:46:06 +00006021 // If we have an icmp le or icmp ge instruction, turn it into the
6022 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6023 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006024 switch (I.getPredicate()) {
6025 default: break;
6026 case ICmpInst::ICMP_ULE:
6027 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006028 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006029 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006030 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006031 case ICmpInst::ICMP_SLE:
6032 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006033 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006034 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006035 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006036 case ICmpInst::ICMP_UGE:
6037 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006038 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006039 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006040 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006041 case ICmpInst::ICMP_SGE:
6042 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006043 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006044 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006045 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006046 }
6047
Chris Lattner183661e2008-07-11 05:40:05 +00006048 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006049 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006050 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006051 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6052 }
6053
6054 // See if we can fold the comparison based on range information we can get
6055 // by checking whether bits are known to be zero or one in the input.
6056 if (BitWidth != 0) {
6057 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6058 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6059
6060 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006061 isSignBit ? APInt::getSignBit(BitWidth)
6062 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006063 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006064 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006065 if (SimplifyDemandedBits(I.getOperandUse(1),
6066 APInt::getAllOnesValue(BitWidth),
6067 Op1KnownZero, Op1KnownOne, 0))
6068 return &I;
6069
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006070 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006071 // in. Compute the Min, Max and RHS values based on the known bits. For the
6072 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006073 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6074 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6075 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6076 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6077 Op0Min, Op0Max);
6078 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6079 Op1Min, Op1Max);
6080 } else {
6081 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6082 Op0Min, Op0Max);
6083 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6084 Op1Min, Op1Max);
6085 }
6086
Chris Lattner183661e2008-07-11 05:40:05 +00006087 // If Min and Max are known to be the same, then SimplifyDemandedBits
6088 // figured out that the LHS is a constant. Just constant fold this now so
6089 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006091 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006092 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006093 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006094 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006095 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096
Chris Lattner183661e2008-07-11 05:40:05 +00006097 // Based on the range information we know about the LHS, see if we can
6098 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006099 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006100 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006101 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006102 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006103 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006104 break;
6105 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006106 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006107 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006108 break;
6109 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006111 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006113 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006115 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6117 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006118 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006119 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120
6121 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6122 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006123 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006124 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 }
Chris Lattner84dff672008-07-11 05:08:55 +00006126 break;
6127 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006129 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006131 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132
6133 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006134 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6136 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006137 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006138 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139
6140 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6141 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006142 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006143 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006144 }
Chris Lattner84dff672008-07-11 05:08:55 +00006145 break;
6146 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006148 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006150 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006152 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6154 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006155 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006156 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006157 }
Chris Lattner84dff672008-07-11 05:08:55 +00006158 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 case ICmpInst::ICMP_SGT:
6160 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006161 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164
6165 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006166 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6168 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006169 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006170 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171 }
6172 break;
6173 case ICmpInst::ICMP_SGE:
6174 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6175 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006176 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006178 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 break;
6180 case ICmpInst::ICMP_SLE:
6181 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6182 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006183 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006185 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 break;
6187 case ICmpInst::ICMP_UGE:
6188 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6189 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006190 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006192 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 break;
6194 case ICmpInst::ICMP_ULE:
6195 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6196 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006197 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006200 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006201 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202
6203 // Turn a signed comparison into an unsigned one if both operands
6204 // are known to have the same sign.
6205 if (I.isSignedPredicate() &&
6206 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6207 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006208 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006209 }
6210
6211 // Test if the ICmpInst instruction is used exclusively by a select as
6212 // part of a minimum or maximum operation. If so, refrain from doing
6213 // any other folding. This helps out other analyses which understand
6214 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6215 // and CodeGen. And in this case, at least one of the comparison
6216 // operands has at least one user besides the compare (the select),
6217 // which would often largely negate the benefit of folding anyway.
6218 if (I.hasOneUse())
6219 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6220 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6221 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6222 return 0;
6223
6224 // See if we are doing a comparison between a constant and an instruction that
6225 // can be folded into the comparison.
6226 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006227 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006228 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006229 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006230 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006231 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6232 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006233 }
6234
Chris Lattner01deb9d2007-04-03 17:43:25 +00006235 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006236 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6237 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6238 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006239 case Instruction::GetElementPtr:
6240 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006241 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006242 bool isAllZeros = true;
6243 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6244 if (!isa<Constant>(LHSI->getOperand(i)) ||
6245 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6246 isAllZeros = false;
6247 break;
6248 }
6249 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006250 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006251 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006252 }
6253 break;
6254
Chris Lattner6970b662005-04-23 15:31:55 +00006255 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006256 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006257 // block. If in the same block, we're encouraging jump threading. If
6258 // not, we are just pessimizing the code by making an i1 phi.
6259 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006260 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006261 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006262 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006263 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006264 // If either operand of the select is a constant, we can fold the
6265 // comparison into the select arms, which will cause one to be
6266 // constant folded and the select turned into a bitwise or.
6267 Value *Op1 = 0, *Op2 = 0;
6268 if (LHSI->hasOneUse()) {
6269 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6270 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006271 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006272 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006273 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6274 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006275 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6276 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006277 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006279 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6280 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006281 }
6282 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006283
Chris Lattner6970b662005-04-23 15:31:55 +00006284 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006285 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006286 break;
6287 }
Chris Lattner4802d902007-04-06 18:57:34 +00006288 case Instruction::Malloc:
6289 // If we have (malloc != null), and if the malloc has a single use, we
6290 // can assume it is successful and remove the malloc.
6291 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006292 Worklist.Add(LHSI);
Victor Hernandez83d63912009-09-18 22:35:49 +00006293 return ReplaceInstUsesWith(I,
6294 ConstantInt::get(Type::getInt1Ty(*Context),
6295 !I.isTrueWhenEqual()));
6296 }
6297 break;
6298 case Instruction::Call:
6299 // If we have (malloc != null), and if the malloc has a single use, we
6300 // can assume it is successful and remove the malloc.
6301 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6302 isa<ConstantPointerNull>(RHSC)) {
6303 Worklist.Add(LHSI);
6304 return ReplaceInstUsesWith(I,
6305 ConstantInt::get(Type::getInt1Ty(*Context),
6306 !I.isTrueWhenEqual()));
6307 }
6308 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006309 }
Chris Lattner6970b662005-04-23 15:31:55 +00006310 }
6311
Reid Spencere4d87aa2006-12-23 06:05:41 +00006312 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006313 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006314 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006315 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006316 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006317 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6318 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006319 return NI;
6320
Reid Spencere4d87aa2006-12-23 06:05:41 +00006321 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006322 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6323 // now.
6324 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6325 if (isa<PointerType>(Op0->getType()) &&
6326 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006327 // We keep moving the cast from the left operand over to the right
6328 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006329 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006330
Chris Lattner57d86372007-01-06 01:45:59 +00006331 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6332 // so eliminate it as well.
6333 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6334 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006335
Chris Lattnerde90b762003-11-03 04:25:02 +00006336 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006337 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006338 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006339 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006340 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006342 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006343 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006344 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006345 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006346 }
Chris Lattner57d86372007-01-06 01:45:59 +00006347 }
6348
6349 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006350 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006351 // This comes up when you have code like
6352 // int X = A < B;
6353 // if (X) ...
6354 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006355 // with a constant or another cast from the same type.
6356 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006357 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006358 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006359 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006360
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006361 // See if it's the same type of instruction on the left and right.
6362 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6363 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006364 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006365 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006366 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006367 default: break;
6368 case Instruction::Add:
6369 case Instruction::Sub:
6370 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006371 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006372 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006373 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006374 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6375 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6376 if (CI->getValue().isSignBit()) {
6377 ICmpInst::Predicate Pred = I.isSignedPredicate()
6378 ? I.getUnsignedPredicate()
6379 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006380 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006381 Op1I->getOperand(0));
6382 }
6383
6384 if (CI->getValue().isMaxSignedValue()) {
6385 ICmpInst::Predicate Pred = I.isSignedPredicate()
6386 ? I.getUnsignedPredicate()
6387 : I.getSignedPredicate();
6388 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006389 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006390 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006391 }
6392 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006393 break;
6394 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006395 if (!I.isEquality())
6396 break;
6397
Nick Lewycky5d52c452008-08-21 05:56:10 +00006398 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6399 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6400 // Mask = -1 >> count-trailing-zeros(Cst).
6401 if (!CI->isZero() && !CI->isOne()) {
6402 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006403 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006404 APInt::getLowBitsSet(AP.getBitWidth(),
6405 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006406 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006407 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6408 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006409 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006410 }
6411 }
6412 break;
6413 }
6414 }
6415 }
6416 }
6417
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006418 // ~x < ~y --> y < x
6419 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006420 if (match(Op0, m_Not(m_Value(A))) &&
6421 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006422 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006423 }
6424
Chris Lattner65b72ba2006-09-18 04:22:48 +00006425 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006426 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006427
6428 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006429 if (match(Op0, m_Neg(m_Value(A))) &&
6430 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006431 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006432
Dan Gohman4ae51262009-08-12 16:23:25 +00006433 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006434 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6435 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006436 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006437 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006438 }
6439
Dan Gohman4ae51262009-08-12 16:23:25 +00006440 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006441 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006442 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006443 if (match(B, m_ConstantInt(C1)) &&
6444 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006445 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006446 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006447 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6448 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006449 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006450
6451 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006452 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6453 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6454 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6455 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006456 }
6457 }
6458
Dan Gohman4ae51262009-08-12 16:23:25 +00006459 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006460 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006461 // A == (A^B) -> B == 0
6462 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006463 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006464 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006465 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006466
6467 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006468 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006469 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006470 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006471
6472 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006473 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006474 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006475 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006476
Chris Lattner9c2328e2006-11-14 06:06:06 +00006477 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6478 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006479 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6480 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006481 Value *X = 0, *Y = 0, *Z = 0;
6482
6483 if (A == C) {
6484 X = B; Y = D; Z = A;
6485 } else if (A == D) {
6486 X = B; Y = C; Z = A;
6487 } else if (B == C) {
6488 X = A; Y = D; Z = B;
6489 } else if (B == D) {
6490 X = A; Y = C; Z = B;
6491 }
6492
6493 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006494 Op1 = Builder->CreateXor(X, Y, "tmp");
6495 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006496 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006497 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006498 return &I;
6499 }
6500 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006501 }
Chris Lattner7e708292002-06-25 16:13:24 +00006502 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006503}
6504
Chris Lattner562ef782007-06-20 23:46:26 +00006505
6506/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6507/// and CmpRHS are both known to be integer constants.
6508Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6509 ConstantInt *DivRHS) {
6510 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6511 const APInt &CmpRHSV = CmpRHS->getValue();
6512
6513 // FIXME: If the operand types don't match the type of the divide
6514 // then don't attempt this transform. The code below doesn't have the
6515 // logic to deal with a signed divide and an unsigned compare (and
6516 // vice versa). This is because (x /s C1) <s C2 produces different
6517 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6518 // (x /u C1) <u C2. Simply casting the operands and result won't
6519 // work. :( The if statement below tests that condition and bails
6520 // if it finds it.
6521 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6522 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6523 return 0;
6524 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006525 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006526 if (DivIsSigned && DivRHS->isAllOnesValue())
6527 return 0; // The overflow computation also screws up here
6528 if (DivRHS->isOne())
6529 return 0; // Not worth bothering, and eliminates some funny cases
6530 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006531
6532 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6533 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6534 // C2 (CI). By solving for X we can turn this into a range check
6535 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006536 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006537
6538 // Determine if the product overflows by seeing if the product is
6539 // not equal to the divide. Make sure we do the same kind of divide
6540 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006541 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6542 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006543
6544 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006545 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006546
Chris Lattner1dbfd482007-06-21 18:11:19 +00006547 // Figure out the interval that is being checked. For example, a comparison
6548 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6549 // Compute this interval based on the constants involved and the signedness of
6550 // the compare/divide. This computes a half-open interval, keeping track of
6551 // whether either value in the interval overflows. After analysis each
6552 // overflow variable is set to 0 if it's corresponding bound variable is valid
6553 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6554 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006555 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006556
Chris Lattner562ef782007-06-20 23:46:26 +00006557 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006558 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006559 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006560 HiOverflow = LoOverflow = ProdOV;
6561 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006562 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006563 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006564 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006565 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006566 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006567 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006568 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006569 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6570 HiOverflow = LoOverflow = ProdOV;
6571 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006572 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006573 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006575 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006576 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6577 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006578 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006579 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006580 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006581 true) ? -1 : 0;
6582 }
Chris Lattner562ef782007-06-20 23:46:26 +00006583 }
Dan Gohman76491272008-02-13 22:09:18 +00006584 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006585 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006587 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006588 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6590 HiOverflow = 1; // [INTMIN+1, overflow)
6591 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6592 }
Dan Gohman76491272008-02-13 22:09:18 +00006593 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006595 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006597 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006598 LoOverflow = AddWithOverflow(LoBound, HiBound,
6599 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006600 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006601 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6602 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006603 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006604 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006605 }
6606
Chris Lattner1dbfd482007-06-21 18:11:19 +00006607 // Dividing by a negative swaps the condition. LT <-> GT
6608 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006609 }
6610
6611 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006612 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006613 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006614 case ICmpInst::ICMP_EQ:
6615 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006616 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006617 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006618 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006619 ICmpInst::ICMP_UGE, X, LoBound);
6620 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006621 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006622 ICmpInst::ICMP_ULT, X, HiBound);
6623 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006625 case ICmpInst::ICMP_NE:
6626 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006627 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006628 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006629 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006630 ICmpInst::ICMP_ULT, X, LoBound);
6631 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006632 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006633 ICmpInst::ICMP_UGE, X, HiBound);
6634 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006635 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006636 case ICmpInst::ICMP_ULT:
6637 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006638 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006639 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006640 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006641 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006642 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006643 case ICmpInst::ICMP_UGT:
6644 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006645 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006646 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006647 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006648 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006649 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006650 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006651 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006652 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006653 }
6654}
6655
6656
Chris Lattner01deb9d2007-04-03 17:43:25 +00006657/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6658///
6659Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6660 Instruction *LHSI,
6661 ConstantInt *RHS) {
6662 const APInt &RHSV = RHS->getValue();
6663
6664 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006665 case Instruction::Trunc:
6666 if (ICI.isEquality() && LHSI->hasOneUse()) {
6667 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6668 // of the high bits truncated out of x are known.
6669 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6670 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6671 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6672 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6673 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6674
6675 // If all the high bits are known, we can do this xform.
6676 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6677 // Pull in the high bits from known-ones set.
6678 APInt NewRHS(RHS->getValue());
6679 NewRHS.zext(SrcBits);
6680 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006681 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006682 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006683 }
6684 }
6685 break;
6686
Duncan Sands0091bf22007-04-04 06:42:45 +00006687 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006688 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6689 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6690 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006691 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6692 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006693 Value *CompareVal = LHSI->getOperand(0);
6694
6695 // If the sign bit of the XorCST is not set, there is no change to
6696 // the operation, just stop using the Xor.
6697 if (!XorCST->getValue().isNegative()) {
6698 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006699 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006700 return &ICI;
6701 }
6702
6703 // Was the old condition true if the operand is positive?
6704 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6705
6706 // If so, the new one isn't.
6707 isTrueIfPositive ^= true;
6708
6709 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006710 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006711 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006712 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006713 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006714 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006715 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006716
6717 if (LHSI->hasOneUse()) {
6718 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6719 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6720 const APInt &SignBit = XorCST->getValue();
6721 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6722 ? ICI.getUnsignedPredicate()
6723 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006724 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006725 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006726 }
6727
6728 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006729 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006730 const APInt &NotSignBit = XorCST->getValue();
6731 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6732 ? ICI.getUnsignedPredicate()
6733 : ICI.getSignedPredicate();
6734 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006735 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006736 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006737 }
6738 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006739 }
6740 break;
6741 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6742 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6743 LHSI->getOperand(0)->hasOneUse()) {
6744 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6745
6746 // If the LHS is an AND of a truncating cast, we can widen the
6747 // and/compare to be the input width without changing the value
6748 // produced, eliminating a cast.
6749 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6750 // We can do this transformation if either the AND constant does not
6751 // have its sign bit set or if it is an equality comparison.
6752 // Extending a relational comparison when we're checking the sign
6753 // bit would not work.
6754 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006755 (ICI.isEquality() ||
6756 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757 uint32_t BitWidth =
6758 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6759 APInt NewCST = AndCST->getValue();
6760 NewCST.zext(BitWidth);
6761 APInt NewCI = RHSV;
6762 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006763 Value *NewAnd =
6764 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006765 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006766 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006767 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006768 }
6769 }
6770
6771 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6772 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6773 // happens a LOT in code produced by the C front-end, for bitfield
6774 // access.
6775 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6776 if (Shift && !Shift->isShift())
6777 Shift = 0;
6778
6779 ConstantInt *ShAmt;
6780 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6781 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6782 const Type *AndTy = AndCST->getType(); // Type of the and.
6783
6784 // We can fold this as long as we can't shift unknown bits
6785 // into the mask. This can only happen with signed shift
6786 // rights, as they sign-extend.
6787 if (ShAmt) {
6788 bool CanFold = Shift->isLogicalShift();
6789 if (!CanFold) {
6790 // To test for the bad case of the signed shr, see if any
6791 // of the bits shifted in could be tested after the mask.
6792 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6793 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6794
6795 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6796 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6797 AndCST->getValue()) == 0)
6798 CanFold = true;
6799 }
6800
6801 if (CanFold) {
6802 Constant *NewCst;
6803 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006804 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006805 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006806 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006807
6808 // Check to see if we are shifting out any of the bits being
6809 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006810 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006811 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006812 // If we shifted bits out, the fold is not going to work out.
6813 // As a special case, check to see if this means that the
6814 // result is always true or false now.
6815 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006816 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006817 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006818 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006819 } else {
6820 ICI.setOperand(1, NewCst);
6821 Constant *NewAndCST;
6822 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006823 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006824 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006825 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006826 LHSI->setOperand(1, NewAndCST);
6827 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006828 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006829 return &ICI;
6830 }
6831 }
6832 }
6833
6834 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6835 // preferable because it allows the C<<Y expression to be hoisted out
6836 // of a loop if Y is invariant and X is not.
6837 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006838 ICI.isEquality() && !Shift->isArithmeticShift() &&
6839 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006840 // Compute C << Y.
6841 Value *NS;
6842 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006843 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006844 } else {
6845 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006846 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006847 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006848
6849 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006850 Value *NewAnd =
6851 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006852
6853 ICI.setOperand(0, NewAnd);
6854 return &ICI;
6855 }
6856 }
6857 break;
6858
Chris Lattnera0141b92007-07-15 20:42:37 +00006859 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6860 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6861 if (!ShAmt) break;
6862
6863 uint32_t TypeBits = RHSV.getBitWidth();
6864
6865 // Check that the shift amount is in range. If not, don't perform
6866 // undefined shifts. When the shift is visited it will be
6867 // simplified.
6868 if (ShAmt->uge(TypeBits))
6869 break;
6870
6871 if (ICI.isEquality()) {
6872 // If we are comparing against bits always shifted out, the
6873 // comparison cannot succeed.
6874 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006875 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006876 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006877 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6878 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006879 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006880 return ReplaceInstUsesWith(ICI, Cst);
6881 }
6882
6883 if (LHSI->hasOneUse()) {
6884 // Otherwise strength reduce the shift into an and.
6885 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6886 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006887 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006888 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006889
Chris Lattner74381062009-08-30 07:44:24 +00006890 Value *And =
6891 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006892 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006893 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006894 }
6895 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006896
6897 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6898 bool TrueIfSigned = false;
6899 if (LHSI->hasOneUse() &&
6900 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6901 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006902 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006903 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006904 Value *And =
6905 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006906 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006907 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006908 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006909 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006910 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006911
6912 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006913 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006914 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006915 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006916 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006917
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006918 // Check that the shift amount is in range. If not, don't perform
6919 // undefined shifts. When the shift is visited it will be
6920 // simplified.
6921 uint32_t TypeBits = RHSV.getBitWidth();
6922 if (ShAmt->uge(TypeBits))
6923 break;
6924
6925 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006926
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006927 // If we are comparing against bits always shifted out, the
6928 // comparison cannot succeed.
6929 APInt Comp = RHSV << ShAmtVal;
6930 if (LHSI->getOpcode() == Instruction::LShr)
6931 Comp = Comp.lshr(ShAmtVal);
6932 else
6933 Comp = Comp.ashr(ShAmtVal);
6934
6935 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6936 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006937 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006938 return ReplaceInstUsesWith(ICI, Cst);
6939 }
6940
6941 // Otherwise, check to see if the bits shifted out are known to be zero.
6942 // If so, we can compare against the unshifted value:
6943 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006944 if (LHSI->hasOneUse() &&
6945 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006946 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006947 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006948 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006949 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006950
Evan Chengf30752c2008-04-23 00:38:06 +00006951 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006952 // Otherwise strength reduce the shift into an and.
6953 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006954 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006955
Chris Lattner74381062009-08-30 07:44:24 +00006956 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6957 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006958 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006959 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006960 }
6961 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006962 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006963
6964 case Instruction::SDiv:
6965 case Instruction::UDiv:
6966 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6967 // Fold this div into the comparison, producing a range check.
6968 // Determine, based on the divide type, what the range is being
6969 // checked. If there is an overflow on the low or high side, remember
6970 // it, otherwise compute the range [low, hi) bounding the new value.
6971 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006972 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6973 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6974 DivRHS))
6975 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006976 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006977
6978 case Instruction::Add:
6979 // Fold: icmp pred (add, X, C1), C2
6980
6981 if (!ICI.isEquality()) {
6982 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6983 if (!LHSC) break;
6984 const APInt &LHSV = LHSC->getValue();
6985
6986 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6987 .subtract(LHSV);
6988
6989 if (ICI.isSignedPredicate()) {
6990 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006991 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006992 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006993 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006994 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006995 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006996 }
6997 } else {
6998 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006999 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007000 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007001 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007002 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007003 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007004 }
7005 }
7006 }
7007 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007008 }
7009
7010 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7011 if (ICI.isEquality()) {
7012 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7013
7014 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7015 // the second operand is a constant, simplify a bit.
7016 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7017 switch (BO->getOpcode()) {
7018 case Instruction::SRem:
7019 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7020 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7021 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7022 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007023 Value *NewRem =
7024 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7025 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007026 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007027 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007028 }
7029 }
7030 break;
7031 case Instruction::Add:
7032 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7033 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7034 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007035 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007036 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007037 } else if (RHSV == 0) {
7038 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7039 // efficiently invertible, or if the add has just this one use.
7040 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7041
Dan Gohman186a6362009-08-12 16:04:34 +00007042 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007043 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007044 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007045 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007046 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007047 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007048 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007049 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007050 }
7051 }
7052 break;
7053 case Instruction::Xor:
7054 // For the xor case, we can xor two constants together, eliminating
7055 // the explicit xor.
7056 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007057 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007058 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007059
7060 // FALLTHROUGH
7061 case Instruction::Sub:
7062 // Replace (([sub|xor] A, B) != 0) with (A != B)
7063 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007064 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007065 BO->getOperand(1));
7066 break;
7067
7068 case Instruction::Or:
7069 // If bits are being or'd in that are not present in the constant we
7070 // are comparing against, then the comparison could never succeed!
7071 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007072 Constant *NotCI = ConstantExpr::getNot(RHS);
7073 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007074 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007075 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007076 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 }
7078 break;
7079
7080 case Instruction::And:
7081 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7082 // If bits are being compared against that are and'd out, then the
7083 // comparison can never succeed!
7084 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007085 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007086 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007087 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007088
7089 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7090 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007091 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007092 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007093 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007094
7095 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007096 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007098 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007099 ICmpInst::Predicate pred = isICMP_NE ?
7100 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007101 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007102 }
7103
7104 // ((X & ~7) == 0) --> X < 8
7105 if (RHSV == 0 && isHighOnes(BOC)) {
7106 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007107 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 ICmpInst::Predicate pred = isICMP_NE ?
7109 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007110 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007111 }
7112 }
7113 default: break;
7114 }
7115 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7116 // Handle icmp {eq|ne} <intrinsic>, intcst.
7117 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007118 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007120 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007121 return &ICI;
7122 }
7123 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124 }
7125 return 0;
7126}
7127
7128/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7129/// We only handle extending casts so far.
7130///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007131Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7132 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007133 Value *LHSCIOp = LHSCI->getOperand(0);
7134 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007135 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007136 Value *RHSCIOp;
7137
Chris Lattner8c756c12007-05-05 22:41:33 +00007138 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7139 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007140 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7141 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007142 cast<IntegerType>(DestTy)->getBitWidth()) {
7143 Value *RHSOp = 0;
7144 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007145 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007146 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7147 RHSOp = RHSC->getOperand(0);
7148 // If the pointer types don't match, insert a bitcast.
7149 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007150 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007151 }
7152
7153 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007154 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007155 }
7156
7157 // The code below only handles extension cast instructions, so far.
7158 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007159 if (LHSCI->getOpcode() != Instruction::ZExt &&
7160 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007161 return 0;
7162
Reid Spencere4d87aa2006-12-23 06:05:41 +00007163 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7164 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007165
Reid Spencere4d87aa2006-12-23 06:05:41 +00007166 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007167 // Not an extension from the same type?
7168 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007169 if (RHSCIOp->getType() != LHSCIOp->getType())
7170 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007171
Nick Lewycky4189a532008-01-28 03:48:02 +00007172 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007173 // and the other is a zext), then we can't handle this.
7174 if (CI->getOpcode() != LHSCI->getOpcode())
7175 return 0;
7176
Nick Lewycky4189a532008-01-28 03:48:02 +00007177 // Deal with equality cases early.
7178 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007179 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007180
7181 // A signed comparison of sign extended values simplifies into a
7182 // signed comparison.
7183 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007184 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007185
7186 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007187 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007188 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007189
Reid Spencere4d87aa2006-12-23 06:05:41 +00007190 // If we aren't dealing with a constant on the RHS, exit early
7191 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7192 if (!CI)
7193 return 0;
7194
7195 // Compute the constant that would happen if we truncated to SrcTy then
7196 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007197 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7198 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007199 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200
7201 // If the re-extended constant didn't change...
7202 if (Res2 == CI) {
7203 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7204 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007205 // %A = sext i16 %X to i32
7206 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007207 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007208 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007209 // because %A may have negative value.
7210 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007211 // However, we allow this when the compare is EQ/NE, because they are
7212 // signless.
7213 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007214 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007215 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007216 }
7217
7218 // The re-extended constant changed so the constant cannot be represented
7219 // in the shorter type. Consequently, we cannot emit a simple comparison.
7220
7221 // First, handle some easy cases. We know the result cannot be equal at this
7222 // point so handle the ICI.isEquality() cases
7223 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007224 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007225 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007226 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007227
7228 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7229 // should have been folded away previously and not enter in here.
7230 Value *Result;
7231 if (isSignedCmp) {
7232 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007233 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007234 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007235 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007236 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007237 } else {
7238 // We're performing an unsigned comparison.
7239 if (isSignedExt) {
7240 // We're performing an unsigned comp with a sign extended value.
7241 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007242 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007243 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007244 } else {
7245 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007246 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007247 }
7248 }
7249
7250 // Finally, return the value computed.
7251 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007252 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007253 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007254
7255 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7256 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7257 "ICmp should be folded!");
7258 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007259 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007260 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007261}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007262
Reid Spencer832254e2007-02-02 02:16:23 +00007263Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7264 return commonShiftTransforms(I);
7265}
7266
7267Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7268 return commonShiftTransforms(I);
7269}
7270
7271Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007272 if (Instruction *R = commonShiftTransforms(I))
7273 return R;
7274
7275 Value *Op0 = I.getOperand(0);
7276
7277 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7278 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7279 if (CSI->isAllOnesValue())
7280 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007281
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007282 // See if we can turn a signed shr into an unsigned shr.
7283 if (MaskedValueIsZero(Op0,
7284 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7285 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7286
7287 // Arithmetic shifting an all-sign-bit value is a no-op.
7288 unsigned NumSignBits = ComputeNumSignBits(Op0);
7289 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7290 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007291
Chris Lattner348f6652007-12-06 01:59:46 +00007292 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007293}
7294
7295Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7296 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007298
7299 // shl X, 0 == X and shr X, 0 == X
7300 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007301 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7302 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007303 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007304
Reid Spencere4d87aa2006-12-23 06:05:41 +00007305 if (isa<UndefValue>(Op0)) {
7306 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007307 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007308 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007309 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007310 }
7311 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007312 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7313 return ReplaceInstUsesWith(I, Op0);
7314 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007315 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007316 }
7317
Dan Gohman9004c8a2009-05-21 02:28:33 +00007318 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007319 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007320 return &I;
7321
Chris Lattner2eefe512004-04-09 19:05:30 +00007322 // Try to fold constant and into select arguments.
7323 if (isa<Constant>(Op0))
7324 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007325 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007326 return R;
7327
Reid Spencerb83eb642006-10-20 07:07:24 +00007328 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007329 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7330 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007331 return 0;
7332}
7333
Reid Spencerb83eb642006-10-20 07:07:24 +00007334Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007335 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007336 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007337
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007338 // See if we can simplify any instructions used by the instruction whose sole
7339 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007340 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007341
Dan Gohmana119de82009-06-14 23:30:43 +00007342 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7343 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007344 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007345 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007346 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007347 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007348 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007349 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007350 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007351 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007352 }
7353
7354 // ((X*C1) << C2) == (X * (C1 << C2))
7355 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7356 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7357 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007358 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007359 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007360
7361 // Try to fold constant and into select arguments.
7362 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7363 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7364 return R;
7365 if (isa<PHINode>(Op0))
7366 if (Instruction *NV = FoldOpIntoPhi(I))
7367 return NV;
7368
Chris Lattner8999dd32007-12-22 09:07:47 +00007369 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7370 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7371 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7372 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7373 // place. Don't try to do this transformation in this case. Also, we
7374 // require that the input operand is a shift-by-constant so that we have
7375 // confidence that the shifts will get folded together. We could do this
7376 // xform in more cases, but it is unlikely to be profitable.
7377 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7378 isa<ConstantInt>(TrOp->getOperand(1))) {
7379 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007380 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007381 // (shift2 (shift1 & 0x00FF), c2)
7382 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007383
7384 // For logical shifts, the truncation has the effect of making the high
7385 // part of the register be zeros. Emulate this by inserting an AND to
7386 // clear the top bits as needed. This 'and' will usually be zapped by
7387 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007388 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7389 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007390 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7391
7392 // The mask we constructed says what the trunc would do if occurring
7393 // between the shifts. We want to know the effect *after* the second
7394 // shift. We know that it is a logical shift by a constant, so adjust the
7395 // mask as appropriate.
7396 if (I.getOpcode() == Instruction::Shl)
7397 MaskV <<= Op1->getZExtValue();
7398 else {
7399 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7400 MaskV = MaskV.lshr(Op1->getZExtValue());
7401 }
7402
Chris Lattner74381062009-08-30 07:44:24 +00007403 // shift1 & 0x00FF
7404 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7405 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007406
7407 // Return the value truncated to the interesting size.
7408 return new TruncInst(And, I.getType());
7409 }
7410 }
7411
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007413 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7414 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7415 Value *V1, *V2;
7416 ConstantInt *CC;
7417 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007418 default: break;
7419 case Instruction::Add:
7420 case Instruction::And:
7421 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007422 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007423 // These operators commute.
7424 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007425 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007426 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007427 m_Specific(Op1)))) {
7428 Value *YS = // (Y << C)
7429 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7430 // (X + (Y << C))
7431 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7432 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007433 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007434 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007435 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007436 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007437
Chris Lattner150f12a2005-09-18 06:30:59 +00007438 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007439 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007440 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007441 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007442 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007443 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007444 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007445 Value *YS = // (Y << C)
7446 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7447 Op0BO->getName());
7448 // X & (CC << C)
7449 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7450 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007451 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007452 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007453 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007454
Reid Spencera07cb7d2007-02-02 14:41:37 +00007455 // FALL THROUGH.
7456 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007457 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007458 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007459 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007460 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007461 Value *YS = // (Y << C)
7462 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7463 // (X + (Y << C))
7464 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7465 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007466 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007467 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007468 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007469 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007470
Chris Lattner13d4ab42006-05-31 21:14:00 +00007471 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007472 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7473 match(Op0BO->getOperand(0),
7474 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007475 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007476 cast<BinaryOperator>(Op0BO->getOperand(0))
7477 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007478 Value *YS = // (Y << C)
7479 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7480 // X & (CC << C)
7481 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7482 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007483
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007484 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007485 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007486
Chris Lattner11021cb2005-09-18 05:12:10 +00007487 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007488 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007489 }
7490
7491
7492 // If the operand is an bitwise operator with a constant RHS, and the
7493 // shift is the only use, we can pull it out of the shift.
7494 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7495 bool isValid = true; // Valid only for And, Or, Xor
7496 bool highBitSet = false; // Transform if high bit of constant set?
7497
7498 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007499 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007500 case Instruction::Add:
7501 isValid = isLeftShift;
7502 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007503 case Instruction::Or:
7504 case Instruction::Xor:
7505 highBitSet = false;
7506 break;
7507 case Instruction::And:
7508 highBitSet = true;
7509 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007510 }
7511
7512 // If this is a signed shift right, and the high bit is modified
7513 // by the logical operation, do not perform the transformation.
7514 // The highBitSet boolean indicates the value of the high bit of
7515 // the constant which would cause it to be modified for this
7516 // operation.
7517 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007518 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007519 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007520
7521 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007522 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007523
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007524 Value *NewShift =
7525 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007526 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007527
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007528 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007529 NewRHS);
7530 }
7531 }
7532 }
7533 }
7534
Chris Lattnerad0124c2006-01-06 07:52:12 +00007535 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007536 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7537 if (ShiftOp && !ShiftOp->isShift())
7538 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007539
Reid Spencerb83eb642006-10-20 07:07:24 +00007540 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007541 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007542 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7543 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007544 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7545 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7546 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007547
Zhou Sheng4351c642007-04-02 08:20:41 +00007548 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007549
7550 const IntegerType *Ty = cast<IntegerType>(I.getType());
7551
7552 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007553 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007554 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7555 // saturates.
7556 if (AmtSum >= TypeBits) {
7557 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007558 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007559 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7560 }
7561
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007562 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007563 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007564 }
7565
7566 if (ShiftOp->getOpcode() == Instruction::LShr &&
7567 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007568 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007569 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007570
Chris Lattnerb87056f2007-02-05 00:57:54 +00007571 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007572 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007573 }
7574
7575 if (ShiftOp->getOpcode() == Instruction::AShr &&
7576 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007577 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007578 if (AmtSum >= TypeBits)
7579 AmtSum = TypeBits-1;
7580
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007581 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007582
Zhou Shenge9e03f62007-03-28 15:02:20 +00007583 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007584 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007585 }
7586
Chris Lattnerb87056f2007-02-05 00:57:54 +00007587 // Okay, if we get here, one shift must be left, and the other shift must be
7588 // right. See if the amounts are equal.
7589 if (ShiftAmt1 == ShiftAmt2) {
7590 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7591 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007592 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007593 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007594 }
7595 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7596 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007597 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007598 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007599 }
7600 // We can simplify ((X << C) >>s C) into a trunc + sext.
7601 // NOTE: we could do this for any C, but that would make 'unusual' integer
7602 // types. For now, just stick to ones well-supported by the code
7603 // generators.
7604 const Type *SExtType = 0;
7605 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007606 case 1 :
7607 case 8 :
7608 case 16 :
7609 case 32 :
7610 case 64 :
7611 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007612 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007613 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007614 default: break;
7615 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007616 if (SExtType)
7617 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 // Otherwise, we can't handle it yet.
7619 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007620 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007621
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007622 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007623 if (I.getOpcode() == Instruction::Shl) {
7624 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7625 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007626 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007627
Reid Spencer55702aa2007-03-25 21:11:44 +00007628 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007629 return BinaryOperator::CreateAnd(Shift,
7630 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007631 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007633 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007634 if (I.getOpcode() == Instruction::LShr) {
7635 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007636 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007637
Reid Spencerd5e30f02007-03-26 17:18:58 +00007638 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007639 return BinaryOperator::CreateAnd(Shift,
7640 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007641 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007642
7643 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7644 } else {
7645 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007646 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007648 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007649 if (I.getOpcode() == Instruction::Shl) {
7650 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7651 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007652 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7653 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654
Reid Spencer55702aa2007-03-25 21:11:44 +00007655 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007656 return BinaryOperator::CreateAnd(Shift,
7657 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007658 }
7659
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007660 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007661 if (I.getOpcode() == Instruction::LShr) {
7662 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007663 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007664
Reid Spencer68d27cf2007-03-26 23:45:51 +00007665 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007666 return BinaryOperator::CreateAnd(Shift,
7667 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007668 }
7669
7670 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007671 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007672 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007673 return 0;
7674}
7675
Chris Lattnera1be5662002-05-02 17:06:02 +00007676
Chris Lattnercfd65102005-10-29 04:36:15 +00007677/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7678/// expression. If so, decompose it, returning some value X, such that Val is
7679/// X*Scale+Offset.
7680///
7681static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007682 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007683 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7684 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007685 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007686 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007687 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007688 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007689 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7690 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7691 if (I->getOpcode() == Instruction::Shl) {
7692 // This is a value scaled by '1 << the shift amt'.
7693 Scale = 1U << RHS->getZExtValue();
7694 Offset = 0;
7695 return I->getOperand(0);
7696 } else if (I->getOpcode() == Instruction::Mul) {
7697 // This value is scaled by 'RHS'.
7698 Scale = RHS->getZExtValue();
7699 Offset = 0;
7700 return I->getOperand(0);
7701 } else if (I->getOpcode() == Instruction::Add) {
7702 // We have X+C. Check to see if we really have (X*C2)+C1,
7703 // where C1 is divisible by C2.
7704 unsigned SubScale;
7705 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007706 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7707 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007708 Offset += RHS->getZExtValue();
7709 Scale = SubScale;
7710 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007711 }
7712 }
7713 }
7714
7715 // Otherwise, we can't look past this.
7716 Scale = 1;
7717 Offset = 0;
7718 return Val;
7719}
7720
7721
Chris Lattnerb3f83972005-10-24 06:03:58 +00007722/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7723/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007724Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007725 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007726 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007727
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007728 BuilderTy AllocaBuilder(*Builder);
7729 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7730
Chris Lattnerb53c2382005-10-24 06:22:12 +00007731 // Remove any uses of AI that are dead.
7732 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007733
Chris Lattnerb53c2382005-10-24 06:22:12 +00007734 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7735 Instruction *User = cast<Instruction>(*UI++);
7736 if (isInstructionTriviallyDead(User)) {
7737 while (UI != E && *UI == User)
7738 ++UI; // If this instruction uses AI more than once, don't break UI.
7739
Chris Lattnerb53c2382005-10-24 06:22:12 +00007740 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007741 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007742 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007743 }
7744 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007745
7746 // This requires TargetData to get the alloca alignment and size information.
7747 if (!TD) return 0;
7748
Chris Lattnerb3f83972005-10-24 06:03:58 +00007749 // Get the type really allocated and the type casted to.
7750 const Type *AllocElTy = AI.getAllocatedType();
7751 const Type *CastElTy = PTy->getElementType();
7752 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007753
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007754 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7755 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007756 if (CastElTyAlign < AllocElTyAlign) return 0;
7757
Chris Lattner39387a52005-10-24 06:35:18 +00007758 // If the allocation has multiple uses, only promote it if we are strictly
7759 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007760 // same, we open the door to infinite loops of various kinds. (A reference
7761 // from a dbg.declare doesn't count as a use for this purpose.)
7762 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7763 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007764
Duncan Sands777d2302009-05-09 07:06:46 +00007765 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7766 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007767 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007768
Chris Lattner455fcc82005-10-29 03:19:53 +00007769 // See if we can satisfy the modulus by pulling a scale out of the array
7770 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007771 unsigned ArraySizeScale;
7772 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007773 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007774 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7775 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007776
Chris Lattner455fcc82005-10-29 03:19:53 +00007777 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7778 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007779 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7780 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007781
Chris Lattner455fcc82005-10-29 03:19:53 +00007782 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7783 Value *Amt = 0;
7784 if (Scale == 1) {
7785 Amt = NumElements;
7786 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007787 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007788 // Insert before the alloca, not before the cast.
7789 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007790 }
7791
Jeff Cohen86796be2007-04-04 16:58:57 +00007792 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007793 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007794 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007795 }
7796
Chris Lattnerb3f83972005-10-24 06:03:58 +00007797 AllocationInst *New;
7798 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007799 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007800 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007801 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7802 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007803 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007804
Dale Johannesena0a66372009-03-05 00:39:02 +00007805 // If the allocation has one real use plus a dbg.declare, just remove the
7806 // declare.
7807 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7808 EraseInstFromFunction(*DI);
7809 }
7810 // If the allocation has multiple real uses, insert a cast and change all
7811 // things that used it to use the new cast. This will also hack on CI, but it
7812 // will die soon.
7813 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007814 // New is the allocation instruction, pointer typed. AI is the original
7815 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007816 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007817 AI.replaceAllUsesWith(NewCast);
7818 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007819 return ReplaceInstUsesWith(CI, New);
7820}
7821
Chris Lattner70074e02006-05-13 02:06:03 +00007822/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007823/// and return it as type Ty without inserting any new casts and without
7824/// changing the computed value. This is used by code that tries to decide
7825/// whether promoting or shrinking integer operations to wider or smaller types
7826/// will allow us to eliminate a truncate or extend.
7827///
7828/// This is a truncation operation if Ty is smaller than V->getType(), or an
7829/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007830///
7831/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7832/// should return true if trunc(V) can be computed by computing V in the smaller
7833/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7834/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7835/// efficiently truncated.
7836///
7837/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7838/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7839/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007840bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007841 unsigned CastOpc,
7842 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007843 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007844 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007845 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007846
7847 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007848 if (!I) return false;
7849
Dan Gohman6de29f82009-06-15 22:12:54 +00007850 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007851
Chris Lattner951626b2007-08-02 06:11:14 +00007852 // If this is an extension or truncate, we can often eliminate it.
7853 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7854 // If this is a cast from the destination type, we can trivially eliminate
7855 // it, and this will remove a cast overall.
7856 if (I->getOperand(0)->getType() == Ty) {
7857 // If the first operand is itself a cast, and is eliminable, do not count
7858 // this as an eliminable cast. We would prefer to eliminate those two
7859 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007860 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007861 ++NumCastsRemoved;
7862 return true;
7863 }
7864 }
7865
7866 // We can't extend or shrink something that has multiple uses: doing so would
7867 // require duplicating the instruction in general, which isn't profitable.
7868 if (!I->hasOneUse()) return false;
7869
Evan Chengf35fd542009-01-15 17:01:23 +00007870 unsigned Opc = I->getOpcode();
7871 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007872 case Instruction::Add:
7873 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007874 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007875 case Instruction::And:
7876 case Instruction::Or:
7877 case Instruction::Xor:
7878 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007879 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007880 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007881 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007882 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007883
Eli Friedman070a9812009-07-13 22:46:01 +00007884 case Instruction::UDiv:
7885 case Instruction::URem: {
7886 // UDiv and URem can be truncated if all the truncated bits are zero.
7887 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7888 uint32_t BitWidth = Ty->getScalarSizeInBits();
7889 if (BitWidth < OrigBitWidth) {
7890 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7891 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7892 MaskedValueIsZero(I->getOperand(1), Mask)) {
7893 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7894 NumCastsRemoved) &&
7895 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7896 NumCastsRemoved);
7897 }
7898 }
7899 break;
7900 }
Chris Lattner46b96052006-11-29 07:18:39 +00007901 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007902 // If we are truncating the result of this SHL, and if it's a shift of a
7903 // constant amount, we can always perform a SHL in a smaller type.
7904 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007905 uint32_t BitWidth = Ty->getScalarSizeInBits();
7906 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007907 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007908 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007909 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007910 }
7911 break;
7912 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007913 // If this is a truncate of a logical shr, we can truncate it to a smaller
7914 // lshr iff we know that the bits we would otherwise be shifting in are
7915 // already zeros.
7916 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007917 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7918 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007919 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007920 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007921 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7922 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007923 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007924 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007925 }
7926 }
Chris Lattner46b96052006-11-29 07:18:39 +00007927 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007928 case Instruction::ZExt:
7929 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007930 case Instruction::Trunc:
7931 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007932 // can safely replace it. Note that replacing it does not reduce the number
7933 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007934 if (Opc == CastOpc)
7935 return true;
7936
7937 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007938 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007939 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007940 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007941 case Instruction::Select: {
7942 SelectInst *SI = cast<SelectInst>(I);
7943 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007944 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007945 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007946 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007947 }
Chris Lattner8114b712008-06-18 04:00:49 +00007948 case Instruction::PHI: {
7949 // We can change a phi if we can change all operands.
7950 PHINode *PN = cast<PHINode>(I);
7951 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7952 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007953 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007954 return false;
7955 return true;
7956 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007957 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007958 // TODO: Can handle more cases here.
7959 break;
7960 }
7961
7962 return false;
7963}
7964
7965/// EvaluateInDifferentType - Given an expression that
7966/// CanEvaluateInDifferentType returns true for, actually insert the code to
7967/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007968Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007969 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007970 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007971 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007972 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007973
7974 // Otherwise, it must be an instruction.
7975 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007976 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007977 unsigned Opc = I->getOpcode();
7978 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007979 case Instruction::Add:
7980 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007981 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007982 case Instruction::And:
7983 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007984 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007985 case Instruction::AShr:
7986 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007987 case Instruction::Shl:
7988 case Instruction::UDiv:
7989 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007990 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007991 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007992 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007993 break;
7994 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007995 case Instruction::Trunc:
7996 case Instruction::ZExt:
7997 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007998 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007999 // just return the source. There's no need to insert it because it is not
8000 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008001 if (I->getOperand(0)->getType() == Ty)
8002 return I->getOperand(0);
8003
Chris Lattner8114b712008-06-18 04:00:49 +00008004 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008005 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008006 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008007 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008008 case Instruction::Select: {
8009 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8010 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8011 Res = SelectInst::Create(I->getOperand(0), True, False);
8012 break;
8013 }
Chris Lattner8114b712008-06-18 04:00:49 +00008014 case Instruction::PHI: {
8015 PHINode *OPN = cast<PHINode>(I);
8016 PHINode *NPN = PHINode::Create(Ty);
8017 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8018 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8019 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8020 }
8021 Res = NPN;
8022 break;
8023 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008024 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008025 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008026 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008027 break;
8028 }
8029
Chris Lattner8114b712008-06-18 04:00:49 +00008030 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008031 return InsertNewInstBefore(Res, *I);
8032}
8033
Reid Spencer3da59db2006-11-27 01:05:10 +00008034/// @brief Implement the transforms common to all CastInst visitors.
8035Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008036 Value *Src = CI.getOperand(0);
8037
Dan Gohman23d9d272007-05-11 21:10:54 +00008038 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008039 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008040 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008041 if (Instruction::CastOps opc =
8042 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8043 // The first cast (CSrc) is eliminable so we need to fix up or replace
8044 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008045 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008046 }
8047 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008048
Reid Spencer3da59db2006-11-27 01:05:10 +00008049 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008050 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8051 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8052 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008053
8054 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008055 if (isa<PHINode>(Src))
8056 if (Instruction *NV = FoldOpIntoPhi(CI))
8057 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008058
Reid Spencer3da59db2006-11-27 01:05:10 +00008059 return 0;
8060}
8061
Chris Lattner46cd5a12009-01-09 05:44:56 +00008062/// FindElementAtOffset - Given a type and a constant offset, determine whether
8063/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008064/// the specified offset. If so, fill them into NewIndices and return the
8065/// resultant element type, otherwise return null.
8066static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8067 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008068 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008069 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008070 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008071 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008072
8073 // Start with the index over the outer type. Note that the type size
8074 // might be zero (even if the offset isn't zero) if the indexed type
8075 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008076 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008077 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008078 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008079 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008080 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008081
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008082 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008083 if (Offset < 0) {
8084 --FirstIdx;
8085 Offset += TySize;
8086 assert(Offset >= 0);
8087 }
8088 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8089 }
8090
Owen Andersoneed707b2009-07-24 23:12:02 +00008091 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008092
8093 // Index into the types. If we fail, set OrigBase to null.
8094 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008095 // Indexing into tail padding between struct/array elements.
8096 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008097 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008098
Chris Lattner46cd5a12009-01-09 05:44:56 +00008099 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8100 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008101 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8102 "Offset must stay within the indexed type");
8103
Chris Lattner46cd5a12009-01-09 05:44:56 +00008104 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008105 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008106
8107 Offset -= SL->getElementOffset(Elt);
8108 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008109 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008110 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008111 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008112 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008113 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008114 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008115 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008116 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008117 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008118 }
8119 }
8120
Chris Lattner3914f722009-01-24 01:00:13 +00008121 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008122}
8123
Chris Lattnerd3e28342007-04-27 17:44:50 +00008124/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8125Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8126 Value *Src = CI.getOperand(0);
8127
Chris Lattnerd3e28342007-04-27 17:44:50 +00008128 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008129 // If casting the result of a getelementptr instruction with no offset, turn
8130 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008131 if (GEP->hasAllZeroIndices()) {
8132 // Changing the cast operand is usually not a good idea but it is safe
8133 // here because the pointer operand is being replaced with another
8134 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008135 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008136 CI.setOperand(0, GEP->getOperand(0));
8137 return &CI;
8138 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008139
8140 // If the GEP has a single use, and the base pointer is a bitcast, and the
8141 // GEP computes a constant offset, see if we can convert these three
8142 // instructions into fewer. This typically happens with unions and other
8143 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008144 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008145 if (GEP->hasAllConstantIndices()) {
8146 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008147 ConstantInt *OffsetV =
8148 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008149 int64_t Offset = OffsetV->getSExtValue();
8150
8151 // Get the base pointer input of the bitcast, and the type it points to.
8152 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8153 const Type *GEPIdxTy =
8154 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008155 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008156 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008157 // If we were able to index down into an element, create the GEP
8158 // and bitcast the result. This eliminates one bitcast, potentially
8159 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008160 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8161 Builder->CreateInBoundsGEP(OrigBase,
8162 NewIndices.begin(), NewIndices.end()) :
8163 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008164 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008165
Chris Lattner46cd5a12009-01-09 05:44:56 +00008166 if (isa<BitCastInst>(CI))
8167 return new BitCastInst(NGEP, CI.getType());
8168 assert(isa<PtrToIntInst>(CI));
8169 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008170 }
8171 }
8172 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008173 }
8174
8175 return commonCastTransforms(CI);
8176}
8177
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008178/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8179/// type like i42. We don't want to introduce operations on random non-legal
8180/// integer types where they don't already exist in the code. In the future,
8181/// we should consider making this based off target-data, so that 32-bit targets
8182/// won't get i64 operations etc.
8183static bool isSafeIntegerType(const Type *Ty) {
8184 switch (Ty->getPrimitiveSizeInBits()) {
8185 case 8:
8186 case 16:
8187 case 32:
8188 case 64:
8189 return true;
8190 default:
8191 return false;
8192 }
8193}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008194
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008195/// commonIntCastTransforms - This function implements the common transforms
8196/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008197Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8198 if (Instruction *Result = commonCastTransforms(CI))
8199 return Result;
8200
8201 Value *Src = CI.getOperand(0);
8202 const Type *SrcTy = Src->getType();
8203 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008204 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8205 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008206
Reid Spencer3da59db2006-11-27 01:05:10 +00008207 // See if we can simplify any instructions used by the LHS whose sole
8208 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008209 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008210 return &CI;
8211
8212 // If the source isn't an instruction or has more than one use then we
8213 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008214 Instruction *SrcI = dyn_cast<Instruction>(Src);
8215 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008216 return 0;
8217
Chris Lattnerc739cd62007-03-03 05:27:34 +00008218 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008219 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008220 // Only do this if the dest type is a simple type, don't convert the
8221 // expression tree to something weird like i93 unless the source is also
8222 // strange.
8223 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008224 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8225 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008226 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008227 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008228 // eliminates the cast, so it is always a win. If this is a zero-extension,
8229 // we need to do an AND to maintain the clear top-part of the computation,
8230 // so we require that the input have eliminated at least one cast. If this
8231 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008232 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008233 bool DoXForm = false;
8234 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008235 switch (CI.getOpcode()) {
8236 default:
8237 // All the others use floating point so we shouldn't actually
8238 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008239 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008240 case Instruction::Trunc:
8241 DoXForm = true;
8242 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008243 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008244 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008245 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008246 // If it's unnecessary to issue an AND to clear the high bits, it's
8247 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008248 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008249 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8250 if (MaskedValueIsZero(TryRes, Mask))
8251 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008252
8253 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008254 if (TryI->use_empty())
8255 EraseInstFromFunction(*TryI);
8256 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008257 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008258 }
Evan Chengf35fd542009-01-15 17:01:23 +00008259 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008260 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008261 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008262 // If we do not have to emit the truncate + sext pair, then it's always
8263 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008264 //
8265 // It's not safe to eliminate the trunc + sext pair if one of the
8266 // eliminated cast is a truncate. e.g.
8267 // t2 = trunc i32 t1 to i16
8268 // t3 = sext i16 t2 to i32
8269 // !=
8270 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008271 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008272 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8273 if (NumSignBits > (DestBitSize - SrcBitSize))
8274 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008275
8276 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008277 if (TryI->use_empty())
8278 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008279 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008280 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008281 }
Evan Chengf35fd542009-01-15 17:01:23 +00008282 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008283
8284 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008285 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8286 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008287 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8288 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008289 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008290 // Just replace this cast with the result.
8291 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008292
Reid Spencer3da59db2006-11-27 01:05:10 +00008293 assert(Res->getType() == DestTy);
8294 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008295 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008296 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008297 // Just replace this cast with the result.
8298 return ReplaceInstUsesWith(CI, Res);
8299 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008300 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008301
8302 // If the high bits are already zero, just replace this cast with the
8303 // result.
8304 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8305 if (MaskedValueIsZero(Res, Mask))
8306 return ReplaceInstUsesWith(CI, Res);
8307
8308 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008309 Constant *C = ConstantInt::get(*Context,
8310 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008311 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008312 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008313 case Instruction::SExt: {
8314 // If the high bits are already filled with sign bit, just replace this
8315 // cast with the result.
8316 unsigned NumSignBits = ComputeNumSignBits(Res);
8317 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008318 return ReplaceInstUsesWith(CI, Res);
8319
Reid Spencer3da59db2006-11-27 01:05:10 +00008320 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008321 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008322 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008323 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008324 }
8325 }
8326
8327 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8328 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8329
8330 switch (SrcI->getOpcode()) {
8331 case Instruction::Add:
8332 case Instruction::Mul:
8333 case Instruction::And:
8334 case Instruction::Or:
8335 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008336 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008337 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8338 // Don't insert two casts unless at least one can be eliminated.
8339 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008340 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008341 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8342 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008343 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008344 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008345 }
8346 }
8347
8348 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8349 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8350 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008351 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008352 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008353 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008354 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008355 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008356 }
8357 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008358
Eli Friedman65445c52009-07-13 21:45:57 +00008359 case Instruction::Shl: {
8360 // Canonicalize trunc inside shl, if we can.
8361 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8362 if (CI && DestBitSize < SrcBitSize &&
8363 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008364 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8365 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008366 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008367 }
8368 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008369 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008370 }
8371 return 0;
8372}
8373
Chris Lattner8a9f5712007-04-11 06:57:46 +00008374Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008375 if (Instruction *Result = commonIntCastTransforms(CI))
8376 return Result;
8377
8378 Value *Src = CI.getOperand(0);
8379 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008380 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8381 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008382
8383 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008384 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008385 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008386 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008387 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008388 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008389 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008390
Chris Lattner4f9797d2009-03-24 18:15:30 +00008391 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8392 ConstantInt *ShAmtV = 0;
8393 Value *ShiftOp = 0;
8394 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008395 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008396 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8397
8398 // Get a mask for the bits shifting in.
8399 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8400 if (MaskedValueIsZero(ShiftOp, Mask)) {
8401 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008402 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008403
8404 // Okay, we can shrink this. Truncate the input, then return a new
8405 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008406 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008407 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008408 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008409 }
8410 }
8411
8412 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008413}
8414
Evan Chengb98a10e2008-03-24 00:21:34 +00008415/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8416/// in order to eliminate the icmp.
8417Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8418 bool DoXform) {
8419 // If we are just checking for a icmp eq of a single bit and zext'ing it
8420 // to an integer, then shift the bit to the appropriate place and then
8421 // cast to integer to avoid the comparison.
8422 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8423 const APInt &Op1CV = Op1C->getValue();
8424
8425 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8426 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8427 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8428 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8429 if (!DoXform) return ICI;
8430
8431 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008432 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008433 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008434 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008435 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008436 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008437
8438 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008439 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008440 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008441 }
8442
8443 return ReplaceInstUsesWith(CI, In);
8444 }
8445
8446
8447
8448 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8449 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8450 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8451 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8452 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8453 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8454 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8455 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8456 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8457 // This only works for EQ and NE
8458 ICI->isEquality()) {
8459 // If Op1C some other power of two, convert:
8460 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8461 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8462 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8463 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8464
8465 APInt KnownZeroMask(~KnownZero);
8466 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8467 if (!DoXform) return ICI;
8468
8469 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8470 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8471 // (X&4) == 2 --> false
8472 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008473 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008474 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008475 return ReplaceInstUsesWith(CI, Res);
8476 }
8477
8478 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8479 Value *In = ICI->getOperand(0);
8480 if (ShiftAmt) {
8481 // Perform a logical shr by shiftamt.
8482 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008483 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8484 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008485 }
8486
8487 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008488 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008489 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008490 }
8491
8492 if (CI.getType() == In->getType())
8493 return ReplaceInstUsesWith(CI, In);
8494 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008495 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008496 }
8497 }
8498 }
8499
8500 return 0;
8501}
8502
Chris Lattner8a9f5712007-04-11 06:57:46 +00008503Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008504 // If one of the common conversion will work ..
8505 if (Instruction *Result = commonIntCastTransforms(CI))
8506 return Result;
8507
8508 Value *Src = CI.getOperand(0);
8509
Chris Lattnera84f47c2009-02-17 20:47:23 +00008510 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8511 // types and if the sizes are just right we can convert this into a logical
8512 // 'and' which will be much cheaper than the pair of casts.
8513 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8514 // Get the sizes of the types involved. We know that the intermediate type
8515 // will be smaller than A or C, but don't know the relation between A and C.
8516 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008517 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8518 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8519 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008520 // If we're actually extending zero bits, then if
8521 // SrcSize < DstSize: zext(a & mask)
8522 // SrcSize == DstSize: a & mask
8523 // SrcSize > DstSize: trunc(a) & mask
8524 if (SrcSize < DstSize) {
8525 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008526 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008527 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008528 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008529 }
8530
8531 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008532 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008533 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008534 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008535 }
8536 if (SrcSize > DstSize) {
8537 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008538 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008539 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008540 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008541 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008542 }
8543 }
8544
Evan Chengb98a10e2008-03-24 00:21:34 +00008545 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8546 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008547
Evan Chengb98a10e2008-03-24 00:21:34 +00008548 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8549 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8550 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8551 // of the (zext icmp) will be transformed.
8552 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8553 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8554 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8555 (transformZExtICmp(LHS, CI, false) ||
8556 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008557 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8558 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008559 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008560 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008561 }
8562
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008563 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008564 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8565 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8566 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8567 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008568 if (TI0->getType() == CI.getType())
8569 return
8570 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008571 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008572 }
8573
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008574 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8575 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8576 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8577 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8578 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8579 And->getOperand(1) == C)
8580 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8581 Value *TI0 = TI->getOperand(0);
8582 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008583 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008584 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008585 return BinaryOperator::CreateXor(NewAnd, ZC);
8586 }
8587 }
8588
Reid Spencer3da59db2006-11-27 01:05:10 +00008589 return 0;
8590}
8591
Chris Lattner8a9f5712007-04-11 06:57:46 +00008592Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008593 if (Instruction *I = commonIntCastTransforms(CI))
8594 return I;
8595
Chris Lattner8a9f5712007-04-11 06:57:46 +00008596 Value *Src = CI.getOperand(0);
8597
Dan Gohman1975d032008-10-30 20:40:10 +00008598 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008599 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008600 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008601 Constant::getAllOnesValue(CI.getType()),
8602 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008603
8604 // See if the value being truncated is already sign extended. If so, just
8605 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008606 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008607 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008608 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8609 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8610 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008611 unsigned NumSignBits = ComputeNumSignBits(Op);
8612
8613 if (OpBits == DestBits) {
8614 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8615 // bits, it is already ready.
8616 if (NumSignBits > DestBits-MidBits)
8617 return ReplaceInstUsesWith(CI, Op);
8618 } else if (OpBits < DestBits) {
8619 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8620 // bits, just sext from i32.
8621 if (NumSignBits > OpBits-MidBits)
8622 return new SExtInst(Op, CI.getType(), "tmp");
8623 } else {
8624 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8625 // bits, just truncate to i32.
8626 if (NumSignBits > OpBits-MidBits)
8627 return new TruncInst(Op, CI.getType(), "tmp");
8628 }
8629 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008630
8631 // If the input is a shl/ashr pair of a same constant, then this is a sign
8632 // extension from a smaller value. If we could trust arbitrary bitwidth
8633 // integers, we could turn this into a truncate to the smaller bit and then
8634 // use a sext for the whole extension. Since we don't, look deeper and check
8635 // for a truncate. If the source and dest are the same type, eliminate the
8636 // trunc and extend and just do shifts. For example, turn:
8637 // %a = trunc i32 %i to i8
8638 // %b = shl i8 %a, 6
8639 // %c = ashr i8 %b, 6
8640 // %d = sext i8 %c to i32
8641 // into:
8642 // %a = shl i32 %i, 30
8643 // %d = ashr i32 %a, 30
8644 Value *A = 0;
8645 ConstantInt *BA = 0, *CA = 0;
8646 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008647 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008648 BA == CA && isa<TruncInst>(A)) {
8649 Value *I = cast<TruncInst>(A)->getOperand(0);
8650 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008651 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8652 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008653 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008654 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008655 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008656 return BinaryOperator::CreateAShr(I, ShAmtV);
8657 }
8658 }
8659
Chris Lattnerba417832007-04-11 06:12:58 +00008660 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008661}
8662
Chris Lattnerb7530652008-01-27 05:29:54 +00008663/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8664/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008665static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008666 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008667 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008668 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008669 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8670 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008671 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008672 return 0;
8673}
8674
8675/// LookThroughFPExtensions - If this is an fp extension instruction, look
8676/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008677static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008678 if (Instruction *I = dyn_cast<Instruction>(V))
8679 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008680 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008681
8682 // If this value is a constant, return the constant in the smallest FP type
8683 // that can accurately represent it. This allows us to turn
8684 // (float)((double)X+2.0) into x+2.0f.
8685 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008686 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008687 return V; // No constant folding of this.
8688 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008689 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008690 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008691 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008692 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008693 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008694 return V;
8695 // Don't try to shrink to various long double types.
8696 }
8697
8698 return V;
8699}
8700
8701Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8702 if (Instruction *I = commonCastTransforms(CI))
8703 return I;
8704
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008705 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008706 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008707 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008708 // many builtins (sqrt, etc).
8709 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8710 if (OpI && OpI->hasOneUse()) {
8711 switch (OpI->getOpcode()) {
8712 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008713 case Instruction::FAdd:
8714 case Instruction::FSub:
8715 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008716 case Instruction::FDiv:
8717 case Instruction::FRem:
8718 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008719 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8720 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008721 if (LHSTrunc->getType() != SrcTy &&
8722 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008723 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008724 // If the source types were both smaller than the destination type of
8725 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008726 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8727 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008728 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8729 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008730 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008731 }
8732 }
8733 break;
8734 }
8735 }
8736 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008737}
8738
8739Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8740 return commonCastTransforms(CI);
8741}
8742
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008743Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008744 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8745 if (OpI == 0)
8746 return commonCastTransforms(FI);
8747
8748 // fptoui(uitofp(X)) --> X
8749 // fptoui(sitofp(X)) --> X
8750 // This is safe if the intermediate type has enough bits in its mantissa to
8751 // accurately represent all values of X. For example, do not do this with
8752 // i64->float->i64. This is also safe for sitofp case, because any negative
8753 // 'X' value would cause an undefined result for the fptoui.
8754 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8755 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008756 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008757 OpI->getType()->getFPMantissaWidth())
8758 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008759
8760 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008761}
8762
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008763Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008764 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8765 if (OpI == 0)
8766 return commonCastTransforms(FI);
8767
8768 // fptosi(sitofp(X)) --> X
8769 // fptosi(uitofp(X)) --> X
8770 // This is safe if the intermediate type has enough bits in its mantissa to
8771 // accurately represent all values of X. For example, do not do this with
8772 // i64->float->i64. This is also safe for sitofp case, because any negative
8773 // 'X' value would cause an undefined result for the fptoui.
8774 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8775 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008776 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008777 OpI->getType()->getFPMantissaWidth())
8778 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008779
8780 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008781}
8782
8783Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8784 return commonCastTransforms(CI);
8785}
8786
8787Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8788 return commonCastTransforms(CI);
8789}
8790
Chris Lattnera0e69692009-03-24 18:35:40 +00008791Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8792 // If the destination integer type is smaller than the intptr_t type for
8793 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8794 // trunc to be exposed to other transforms. Don't do this for extending
8795 // ptrtoint's, because we don't know if the target sign or zero extends its
8796 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008797 if (TD &&
8798 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008799 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8800 TD->getIntPtrType(CI.getContext()),
8801 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008802 return new TruncInst(P, CI.getType());
8803 }
8804
Chris Lattnerd3e28342007-04-27 17:44:50 +00008805 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008806}
8807
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008808Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008809 // If the source integer type is larger than the intptr_t type for
8810 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8811 // allows the trunc to be exposed to other transforms. Don't do this for
8812 // extending inttoptr's, because we don't know if the target sign or zero
8813 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008814 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008815 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008816 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8817 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008818 return new IntToPtrInst(P, CI.getType());
8819 }
8820
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008821 if (Instruction *I = commonCastTransforms(CI))
8822 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008823
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008824 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008825}
8826
Chris Lattnerd3e28342007-04-27 17:44:50 +00008827Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008828 // If the operands are integer typed then apply the integer transforms,
8829 // otherwise just apply the common ones.
8830 Value *Src = CI.getOperand(0);
8831 const Type *SrcTy = Src->getType();
8832 const Type *DestTy = CI.getType();
8833
Eli Friedman7e25d452009-07-13 20:53:00 +00008834 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008835 if (Instruction *I = commonPointerCastTransforms(CI))
8836 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008837 } else {
8838 if (Instruction *Result = commonCastTransforms(CI))
8839 return Result;
8840 }
8841
8842
8843 // Get rid of casts from one type to the same type. These are useless and can
8844 // be replaced by the operand.
8845 if (DestTy == Src->getType())
8846 return ReplaceInstUsesWith(CI, Src);
8847
Reid Spencer3da59db2006-11-27 01:05:10 +00008848 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008849 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8850 const Type *DstElTy = DstPTy->getElementType();
8851 const Type *SrcElTy = SrcPTy->getElementType();
8852
Nate Begeman83ad90a2008-03-31 00:22:16 +00008853 // If the address spaces don't match, don't eliminate the bitcast, which is
8854 // required for changing types.
8855 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8856 return 0;
8857
Victor Hernandez83d63912009-09-18 22:35:49 +00008858 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008859 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008860 // There is no need to modify malloc calls because it is their bitcast that
8861 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008862 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8863 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8864 return V;
8865
Chris Lattnerd717c182007-05-05 22:32:24 +00008866 // If the source and destination are pointers, and this cast is equivalent
8867 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008868 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008869 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008870 unsigned NumZeros = 0;
8871 while (SrcElTy != DstElTy &&
8872 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8873 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8874 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8875 ++NumZeros;
8876 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008877
Chris Lattnerd3e28342007-04-27 17:44:50 +00008878 // If we found a path from the src to dest, create the getelementptr now.
8879 if (SrcElTy == DstElTy) {
8880 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008881 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8882 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008883 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008884 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008885
Eli Friedman2451a642009-07-18 23:06:53 +00008886 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8887 if (DestVTy->getNumElements() == 1) {
8888 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008889 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008890 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008891 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008892 }
8893 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8894 }
8895 }
8896
8897 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8898 if (SrcVTy->getNumElements() == 1) {
8899 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008900 Value *Elem =
8901 Builder->CreateExtractElement(Src,
8902 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008903 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8904 }
8905 }
8906 }
8907
Reid Spencer3da59db2006-11-27 01:05:10 +00008908 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8909 if (SVI->hasOneUse()) {
8910 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8911 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008912 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008913 cast<VectorType>(DestTy)->getNumElements() ==
8914 SVI->getType()->getNumElements() &&
8915 SVI->getType()->getNumElements() ==
8916 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008917 CastInst *Tmp;
8918 // If either of the operands is a cast from CI.getType(), then
8919 // evaluating the shuffle in the casted destination's type will allow
8920 // us to eliminate at least one cast.
8921 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8922 Tmp->getOperand(0)->getType() == DestTy) ||
8923 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8924 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008925 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8926 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008927 // Return a new shuffle vector. Use the same element ID's, as we
8928 // know the vector types match #elts.
8929 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008930 }
8931 }
8932 }
8933 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008934 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008935}
8936
Chris Lattnere576b912004-04-09 23:46:01 +00008937/// GetSelectFoldableOperands - We want to turn code that looks like this:
8938/// %C = or %A, %B
8939/// %D = select %cond, %C, %A
8940/// into:
8941/// %C = select %cond, %B, 0
8942/// %D = or %A, %C
8943///
8944/// Assuming that the specified instruction is an operand to the select, return
8945/// a bitmask indicating which operands of this instruction are foldable if they
8946/// equal the other incoming value of the select.
8947///
8948static unsigned GetSelectFoldableOperands(Instruction *I) {
8949 switch (I->getOpcode()) {
8950 case Instruction::Add:
8951 case Instruction::Mul:
8952 case Instruction::And:
8953 case Instruction::Or:
8954 case Instruction::Xor:
8955 return 3; // Can fold through either operand.
8956 case Instruction::Sub: // Can only fold on the amount subtracted.
8957 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008958 case Instruction::LShr:
8959 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008960 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008961 default:
8962 return 0; // Cannot fold
8963 }
8964}
8965
8966/// GetSelectFoldableConstant - For the same transformation as the previous
8967/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008968static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008969 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008970 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008971 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008972 case Instruction::Add:
8973 case Instruction::Sub:
8974 case Instruction::Or:
8975 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008976 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008977 case Instruction::LShr:
8978 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008979 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008980 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008981 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008982 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008983 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008984 }
8985}
8986
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008987/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8988/// have the same opcode and only one use each. Try to simplify this.
8989Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8990 Instruction *FI) {
8991 if (TI->getNumOperands() == 1) {
8992 // If this is a non-volatile load or a cast from the same type,
8993 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008994 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008995 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8996 return 0;
8997 } else {
8998 return 0; // unknown unary op.
8999 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009000
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009001 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009002 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009003 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009004 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009005 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009006 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009007 }
9008
Reid Spencer832254e2007-02-02 02:16:23 +00009009 // Only handle binary operators here.
9010 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009011 return 0;
9012
9013 // Figure out if the operations have any operands in common.
9014 Value *MatchOp, *OtherOpT, *OtherOpF;
9015 bool MatchIsOpZero;
9016 if (TI->getOperand(0) == FI->getOperand(0)) {
9017 MatchOp = TI->getOperand(0);
9018 OtherOpT = TI->getOperand(1);
9019 OtherOpF = FI->getOperand(1);
9020 MatchIsOpZero = true;
9021 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9022 MatchOp = TI->getOperand(1);
9023 OtherOpT = TI->getOperand(0);
9024 OtherOpF = FI->getOperand(0);
9025 MatchIsOpZero = false;
9026 } else if (!TI->isCommutative()) {
9027 return 0;
9028 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9029 MatchOp = TI->getOperand(0);
9030 OtherOpT = TI->getOperand(1);
9031 OtherOpF = FI->getOperand(0);
9032 MatchIsOpZero = true;
9033 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9034 MatchOp = TI->getOperand(1);
9035 OtherOpT = TI->getOperand(0);
9036 OtherOpF = FI->getOperand(1);
9037 MatchIsOpZero = true;
9038 } else {
9039 return 0;
9040 }
9041
9042 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009043 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9044 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009045 InsertNewInstBefore(NewSI, SI);
9046
9047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9048 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009049 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009050 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009051 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009052 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009053 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009054 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009055}
9056
Evan Chengde621922009-03-31 20:42:45 +00009057static bool isSelect01(Constant *C1, Constant *C2) {
9058 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9059 if (!C1I)
9060 return false;
9061 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9062 if (!C2I)
9063 return false;
9064 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9065}
9066
9067/// FoldSelectIntoOp - Try fold the select into one of the operands to
9068/// facilitate further optimization.
9069Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9070 Value *FalseVal) {
9071 // See the comment above GetSelectFoldableOperands for a description of the
9072 // transformation we are doing here.
9073 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9074 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9075 !isa<Constant>(FalseVal)) {
9076 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9077 unsigned OpToFold = 0;
9078 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9079 OpToFold = 1;
9080 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9081 OpToFold = 2;
9082 }
9083
9084 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009085 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009086 Value *OOp = TVI->getOperand(2-OpToFold);
9087 // Avoid creating select between 2 constants unless it's selecting
9088 // between 0 and 1.
9089 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9090 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9091 InsertNewInstBefore(NewSel, SI);
9092 NewSel->takeName(TVI);
9093 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9094 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009095 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009096 }
9097 }
9098 }
9099 }
9100 }
9101
9102 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9103 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9104 !isa<Constant>(TrueVal)) {
9105 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9106 unsigned OpToFold = 0;
9107 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9108 OpToFold = 1;
9109 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9110 OpToFold = 2;
9111 }
9112
9113 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009114 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009115 Value *OOp = FVI->getOperand(2-OpToFold);
9116 // Avoid creating select between 2 constants unless it's selecting
9117 // between 0 and 1.
9118 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9119 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9120 InsertNewInstBefore(NewSel, SI);
9121 NewSel->takeName(FVI);
9122 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9123 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009124 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009125 }
9126 }
9127 }
9128 }
9129 }
9130
9131 return 0;
9132}
9133
Dan Gohman81b28ce2008-09-16 18:46:06 +00009134/// visitSelectInstWithICmp - Visit a SelectInst that has an
9135/// ICmpInst as its first operand.
9136///
9137Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9138 ICmpInst *ICI) {
9139 bool Changed = false;
9140 ICmpInst::Predicate Pred = ICI->getPredicate();
9141 Value *CmpLHS = ICI->getOperand(0);
9142 Value *CmpRHS = ICI->getOperand(1);
9143 Value *TrueVal = SI.getTrueValue();
9144 Value *FalseVal = SI.getFalseValue();
9145
9146 // Check cases where the comparison is with a constant that
9147 // can be adjusted to fit the min/max idiom. We may edit ICI in
9148 // place here, so make sure the select is the only user.
9149 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009150 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009151 switch (Pred) {
9152 default: break;
9153 case ICmpInst::ICMP_ULT:
9154 case ICmpInst::ICMP_SLT: {
9155 // X < MIN ? T : F --> F
9156 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9157 return ReplaceInstUsesWith(SI, FalseVal);
9158 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009159 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009160 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9161 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9162 Pred = ICmpInst::getSwappedPredicate(Pred);
9163 CmpRHS = AdjustedRHS;
9164 std::swap(FalseVal, TrueVal);
9165 ICI->setPredicate(Pred);
9166 ICI->setOperand(1, CmpRHS);
9167 SI.setOperand(1, TrueVal);
9168 SI.setOperand(2, FalseVal);
9169 Changed = true;
9170 }
9171 break;
9172 }
9173 case ICmpInst::ICMP_UGT:
9174 case ICmpInst::ICMP_SGT: {
9175 // X > MAX ? T : F --> F
9176 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9177 return ReplaceInstUsesWith(SI, FalseVal);
9178 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009179 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009180 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9181 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9182 Pred = ICmpInst::getSwappedPredicate(Pred);
9183 CmpRHS = AdjustedRHS;
9184 std::swap(FalseVal, TrueVal);
9185 ICI->setPredicate(Pred);
9186 ICI->setOperand(1, CmpRHS);
9187 SI.setOperand(1, TrueVal);
9188 SI.setOperand(2, FalseVal);
9189 Changed = true;
9190 }
9191 break;
9192 }
9193 }
9194
Dan Gohman1975d032008-10-30 20:40:10 +00009195 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9196 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009197 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009198 if (match(TrueVal, m_ConstantInt<-1>()) &&
9199 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009200 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009201 else if (match(TrueVal, m_ConstantInt<0>()) &&
9202 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009203 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9204
Dan Gohman1975d032008-10-30 20:40:10 +00009205 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9206 // If we are just checking for a icmp eq of a single bit and zext'ing it
9207 // to an integer, then shift the bit to the appropriate place and then
9208 // cast to integer to avoid the comparison.
9209 const APInt &Op1CV = CI->getValue();
9210
9211 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9212 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9213 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009214 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009215 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009216 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009217 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009218 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009219 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009220 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009221 if (In->getType() != SI.getType())
9222 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009223 true/*SExt*/, "tmp", ICI);
9224
9225 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009226 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009227 In->getName()+".not"), *ICI);
9228
9229 return ReplaceInstUsesWith(SI, In);
9230 }
9231 }
9232 }
9233
Dan Gohman81b28ce2008-09-16 18:46:06 +00009234 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9235 // Transform (X == Y) ? X : Y -> Y
9236 if (Pred == ICmpInst::ICMP_EQ)
9237 return ReplaceInstUsesWith(SI, FalseVal);
9238 // Transform (X != Y) ? X : Y -> X
9239 if (Pred == ICmpInst::ICMP_NE)
9240 return ReplaceInstUsesWith(SI, TrueVal);
9241 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9242
9243 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9244 // Transform (X == Y) ? Y : X -> X
9245 if (Pred == ICmpInst::ICMP_EQ)
9246 return ReplaceInstUsesWith(SI, FalseVal);
9247 // Transform (X != Y) ? Y : X -> Y
9248 if (Pred == ICmpInst::ICMP_NE)
9249 return ReplaceInstUsesWith(SI, TrueVal);
9250 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9251 }
9252
9253 /// NOTE: if we wanted to, this is where to detect integer ABS
9254
9255 return Changed ? &SI : 0;
9256}
9257
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009258/// isDefinedInBB - Return true if the value is an instruction defined in the
9259/// specified basicblock.
9260static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9261 const Instruction *I = dyn_cast<Instruction>(V);
9262 return I != 0 && I->getParent() == BB;
9263}
9264
9265
Chris Lattner3d69f462004-03-12 05:52:32 +00009266Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009267 Value *CondVal = SI.getCondition();
9268 Value *TrueVal = SI.getTrueValue();
9269 Value *FalseVal = SI.getFalseValue();
9270
9271 // select true, X, Y -> X
9272 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009273 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009274 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009275
9276 // select C, X, X -> X
9277 if (TrueVal == FalseVal)
9278 return ReplaceInstUsesWith(SI, TrueVal);
9279
Chris Lattnere87597f2004-10-16 18:11:37 +00009280 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9281 return ReplaceInstUsesWith(SI, FalseVal);
9282 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9283 return ReplaceInstUsesWith(SI, TrueVal);
9284 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9285 if (isa<Constant>(TrueVal))
9286 return ReplaceInstUsesWith(SI, TrueVal);
9287 else
9288 return ReplaceInstUsesWith(SI, FalseVal);
9289 }
9290
Owen Anderson1d0be152009-08-13 21:58:54 +00009291 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009292 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009293 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009294 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009295 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009296 } else {
9297 // Change: A = select B, false, C --> A = and !B, C
9298 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009299 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009300 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009301 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009302 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009303 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009304 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009305 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009306 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009307 } else {
9308 // Change: A = select B, C, true --> A = or !B, C
9309 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009310 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009311 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009312 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009313 }
9314 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009315
9316 // select a, b, a -> a&b
9317 // select a, a, b -> a|b
9318 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009319 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009320 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009321 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009322 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009323
Chris Lattner2eefe512004-04-09 19:05:30 +00009324 // Selecting between two integer constants?
9325 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9326 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009327 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009328 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009329 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009330 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009331 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009332 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009333 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009334 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009335 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009336 }
Chris Lattner457dd822004-06-09 07:59:58 +00009337
Reid Spencere4d87aa2006-12-23 06:05:41 +00009338 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009339 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009340 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009341 // non-constant value, eliminate this whole mess. This corresponds to
9342 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009343 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009344 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009345 cast<Constant>(IC->getOperand(1))->isNullValue())
9346 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9347 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009348 isa<ConstantInt>(ICA->getOperand(1)) &&
9349 (ICA->getOperand(1) == TrueValC ||
9350 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009351 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9352 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009353 // know whether we have a icmp_ne or icmp_eq and whether the
9354 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009355 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009356 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009357 Value *V = ICA;
9358 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009359 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009360 Instruction::Xor, V, ICA->getOperand(1)), SI);
9361 return ReplaceInstUsesWith(SI, V);
9362 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009363 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009364 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009365
9366 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009367 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9368 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009369 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009370 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9371 // This is not safe in general for floating point:
9372 // consider X== -0, Y== +0.
9373 // It becomes safe if either operand is a nonzero constant.
9374 ConstantFP *CFPt, *CFPf;
9375 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9376 !CFPt->getValueAPF().isZero()) ||
9377 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9378 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009379 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009380 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009381 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009382 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009383 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009384 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009385
Reid Spencere4d87aa2006-12-23 06:05:41 +00009386 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009387 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009388 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9389 // This is not safe in general for floating point:
9390 // consider X== -0, Y== +0.
9391 // It becomes safe if either operand is a nonzero constant.
9392 ConstantFP *CFPt, *CFPf;
9393 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9394 !CFPt->getValueAPF().isZero()) ||
9395 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9396 !CFPf->getValueAPF().isZero()))
9397 return ReplaceInstUsesWith(SI, FalseVal);
9398 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009399 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009400 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9401 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009402 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009403 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009404 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009405 }
9406
9407 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009408 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9409 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9410 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009411
Chris Lattner87875da2005-01-13 22:52:24 +00009412 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9413 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9414 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009415 Instruction *AddOp = 0, *SubOp = 0;
9416
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009417 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9418 if (TI->getOpcode() == FI->getOpcode())
9419 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9420 return IV;
9421
9422 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9423 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009424 if ((TI->getOpcode() == Instruction::Sub &&
9425 FI->getOpcode() == Instruction::Add) ||
9426 (TI->getOpcode() == Instruction::FSub &&
9427 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009428 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009429 } else if ((FI->getOpcode() == Instruction::Sub &&
9430 TI->getOpcode() == Instruction::Add) ||
9431 (FI->getOpcode() == Instruction::FSub &&
9432 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009433 AddOp = TI; SubOp = FI;
9434 }
9435
9436 if (AddOp) {
9437 Value *OtherAddOp = 0;
9438 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9439 OtherAddOp = AddOp->getOperand(1);
9440 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9441 OtherAddOp = AddOp->getOperand(0);
9442 }
9443
9444 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009445 // So at this point we know we have (Y -> OtherAddOp):
9446 // select C, (add X, Y), (sub X, Z)
9447 Value *NegVal; // Compute -Z
9448 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009449 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009450 } else {
9451 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009452 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009453 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009454 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009455
9456 Value *NewTrueOp = OtherAddOp;
9457 Value *NewFalseOp = NegVal;
9458 if (AddOp != TI)
9459 std::swap(NewTrueOp, NewFalseOp);
9460 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009461 SelectInst::Create(CondVal, NewTrueOp,
9462 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009463
9464 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009465 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009466 }
9467 }
9468 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009469
Chris Lattnere576b912004-04-09 23:46:01 +00009470 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009471 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009472 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9473 if (FoldI)
9474 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009475 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009476
Chris Lattner5d1704d2009-09-27 19:57:57 +00009477 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009478 // to be live in the predecessor blocks. If they are instructions in SI's
9479 // block, we can't map to the predecessor.
Chris Lattner5d1704d2009-09-27 19:57:57 +00009480 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009481 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9482 isa<PHINode>(SI.getTrueValue())) &&
9483 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9484 isa<PHINode>(SI.getFalseValue())))
Chris Lattner5d1704d2009-09-27 19:57:57 +00009485 if (Instruction *NV = FoldOpIntoPhi(SI))
9486 return NV;
9487
Chris Lattnera1df33c2005-04-24 07:30:14 +00009488 if (BinaryOperator::isNot(CondVal)) {
9489 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9490 SI.setOperand(1, FalseVal);
9491 SI.setOperand(2, TrueVal);
9492 return &SI;
9493 }
9494
Chris Lattner3d69f462004-03-12 05:52:32 +00009495 return 0;
9496}
9497
Dan Gohmaneee962e2008-04-10 18:43:06 +00009498/// EnforceKnownAlignment - If the specified pointer points to an object that
9499/// we control, modify the object's alignment to PrefAlign. This isn't
9500/// often possible though. If alignment is important, a more reliable approach
9501/// is to simply align all global variables and allocation instructions to
9502/// their preferred alignment from the beginning.
9503///
9504static unsigned EnforceKnownAlignment(Value *V,
9505 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009506
Dan Gohmaneee962e2008-04-10 18:43:06 +00009507 User *U = dyn_cast<User>(V);
9508 if (!U) return Align;
9509
Dan Gohmanca178902009-07-17 20:47:02 +00009510 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009511 default: break;
9512 case Instruction::BitCast:
9513 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9514 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009515 // If all indexes are zero, it is just the alignment of the base pointer.
9516 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009517 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009518 if (!isa<Constant>(*i) ||
9519 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009520 AllZeroOperands = false;
9521 break;
9522 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009523
9524 if (AllZeroOperands) {
9525 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009526 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009527 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009528 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009529 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009530 }
9531
9532 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9533 // If there is a large requested alignment and we can, bump up the alignment
9534 // of the global.
9535 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009536 if (GV->getAlignment() >= PrefAlign)
9537 Align = GV->getAlignment();
9538 else {
9539 GV->setAlignment(PrefAlign);
9540 Align = PrefAlign;
9541 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009542 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009543 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9544 // If there is a requested alignment and if this is an alloca, round up.
9545 if (AI->getAlignment() >= PrefAlign)
9546 Align = AI->getAlignment();
9547 else {
9548 AI->setAlignment(PrefAlign);
9549 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009550 }
9551 }
9552
9553 return Align;
9554}
9555
9556/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9557/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9558/// and it is more than the alignment of the ultimate object, see if we can
9559/// increase the alignment of the ultimate object, making this check succeed.
9560unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9561 unsigned PrefAlign) {
9562 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9563 sizeof(PrefAlign) * CHAR_BIT;
9564 APInt Mask = APInt::getAllOnesValue(BitWidth);
9565 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9566 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9567 unsigned TrailZ = KnownZero.countTrailingOnes();
9568 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9569
9570 if (PrefAlign > Align)
9571 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9572
9573 // We don't need to make any adjustment.
9574 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009575}
9576
Chris Lattnerf497b022008-01-13 23:50:23 +00009577Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009578 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009579 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009580 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009581 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009582
9583 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009584 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009585 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009586 return MI;
9587 }
9588
9589 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9590 // load/store.
9591 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9592 if (MemOpLength == 0) return 0;
9593
Chris Lattner37ac6082008-01-14 00:28:35 +00009594 // Source and destination pointer types are always "i8*" for intrinsic. See
9595 // if the size is something we can handle with a single primitive load/store.
9596 // A single load+store correctly handles overlapping memory in the memmove
9597 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009598 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009599 if (Size == 0) return MI; // Delete this mem transfer.
9600
9601 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009602 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009603
Chris Lattner37ac6082008-01-14 00:28:35 +00009604 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009605 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009606 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009607
9608 // Memcpy forces the use of i8* for the source and destination. That means
9609 // that if you're using memcpy to move one double around, you'll get a cast
9610 // from double* to i8*. We'd much rather use a double load+store rather than
9611 // an i64 load+store, here because this improves the odds that the source or
9612 // dest address will be promotable. See if we can find a better type than the
9613 // integer datatype.
9614 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9615 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009616 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009617 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9618 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009619 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009620 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9621 if (STy->getNumElements() == 1)
9622 SrcETy = STy->getElementType(0);
9623 else
9624 break;
9625 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9626 if (ATy->getNumElements() == 1)
9627 SrcETy = ATy->getElementType();
9628 else
9629 break;
9630 } else
9631 break;
9632 }
9633
Dan Gohman8f8e2692008-05-23 01:52:21 +00009634 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009635 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009636 }
9637 }
9638
9639
Chris Lattnerf497b022008-01-13 23:50:23 +00009640 // If the memcpy/memmove provides better alignment info than we can
9641 // infer, use it.
9642 SrcAlign = std::max(SrcAlign, CopyAlign);
9643 DstAlign = std::max(DstAlign, CopyAlign);
9644
Chris Lattner08142f22009-08-30 19:47:22 +00009645 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9646 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009647 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9648 InsertNewInstBefore(L, *MI);
9649 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9650
9651 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009652 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009653 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009654}
Chris Lattner3d69f462004-03-12 05:52:32 +00009655
Chris Lattner69ea9d22008-04-30 06:39:11 +00009656Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9657 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009658 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009659 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009660 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009661 return MI;
9662 }
9663
9664 // Extract the length and alignment and fill if they are constant.
9665 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9666 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009667 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009668 return 0;
9669 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009670 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009671
9672 // If the length is zero, this is a no-op
9673 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9674
9675 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9676 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009677 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009678
9679 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009680 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009681
9682 // Alignment 0 is identity for alignment 1 for memset, but not store.
9683 if (Alignment == 0) Alignment = 1;
9684
9685 // Extract the fill value and store.
9686 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009687 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009688 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009689
9690 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009691 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009692 return MI;
9693 }
9694
9695 return 0;
9696}
9697
9698
Chris Lattner8b0ea312006-01-13 20:11:04 +00009699/// visitCallInst - CallInst simplification. This mostly only handles folding
9700/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9701/// the heavy lifting.
9702///
Chris Lattner9fe38862003-06-19 17:00:31 +00009703Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009704 // If the caller function is nounwind, mark the call as nounwind, even if the
9705 // callee isn't.
9706 if (CI.getParent()->getParent()->doesNotThrow() &&
9707 !CI.doesNotThrow()) {
9708 CI.setDoesNotThrow();
9709 return &CI;
9710 }
9711
Chris Lattner8b0ea312006-01-13 20:11:04 +00009712 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9713 if (!II) return visitCallSite(&CI);
9714
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009715 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9716 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009717 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009718 bool Changed = false;
9719
9720 // memmove/cpy/set of zero bytes is a noop.
9721 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9722 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9723
Chris Lattner35b9e482004-10-12 04:52:52 +00009724 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009725 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009726 // Replace the instruction with just byte operations. We would
9727 // transform other cases to loads/stores, but we don't know if
9728 // alignment is sufficient.
9729 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009730 }
9731
Chris Lattner35b9e482004-10-12 04:52:52 +00009732 // If we have a memmove and the source operation is a constant global,
9733 // then the source and dest pointers can't alias, so we can change this
9734 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009735 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009736 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9737 if (GVSrc->isConstant()) {
9738 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009739 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9740 const Type *Tys[1];
9741 Tys[0] = CI.getOperand(3)->getType();
9742 CI.setOperand(0,
9743 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009744 Changed = true;
9745 }
Chris Lattnera935db82008-05-28 05:30:41 +00009746
9747 // memmove(x,x,size) -> noop.
9748 if (MMI->getSource() == MMI->getDest())
9749 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009750 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009751
Chris Lattner95a959d2006-03-06 20:18:44 +00009752 // If we can determine a pointer alignment that is bigger than currently
9753 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009754 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009755 if (Instruction *I = SimplifyMemTransfer(MI))
9756 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009757 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9758 if (Instruction *I = SimplifyMemSet(MSI))
9759 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009760 }
9761
Chris Lattner8b0ea312006-01-13 20:11:04 +00009762 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009763 }
9764
9765 switch (II->getIntrinsicID()) {
9766 default: break;
9767 case Intrinsic::bswap:
9768 // bswap(bswap(x)) -> x
9769 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9770 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9771 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9772 break;
9773 case Intrinsic::ppc_altivec_lvx:
9774 case Intrinsic::ppc_altivec_lvxl:
9775 case Intrinsic::x86_sse_loadu_ps:
9776 case Intrinsic::x86_sse2_loadu_pd:
9777 case Intrinsic::x86_sse2_loadu_dq:
9778 // Turn PPC lvx -> load if the pointer is known aligned.
9779 // Turn X86 loadups -> load if the pointer is known aligned.
9780 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009781 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9782 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009783 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009784 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009785 break;
9786 case Intrinsic::ppc_altivec_stvx:
9787 case Intrinsic::ppc_altivec_stvxl:
9788 // Turn stvx -> store if the pointer is known aligned.
9789 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9790 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009791 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009792 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009793 return new StoreInst(II->getOperand(1), Ptr);
9794 }
9795 break;
9796 case Intrinsic::x86_sse_storeu_ps:
9797 case Intrinsic::x86_sse2_storeu_pd:
9798 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009799 // Turn X86 storeu -> store if the pointer is known aligned.
9800 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9801 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009802 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009803 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009804 return new StoreInst(II->getOperand(2), Ptr);
9805 }
9806 break;
9807
9808 case Intrinsic::x86_sse_cvttss2si: {
9809 // These intrinsics only demands the 0th element of its input vector. If
9810 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009811 unsigned VWidth =
9812 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9813 APInt DemandedElts(VWidth, 1);
9814 APInt UndefElts(VWidth, 0);
9815 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009816 UndefElts)) {
9817 II->setOperand(1, V);
9818 return II;
9819 }
9820 break;
9821 }
9822
9823 case Intrinsic::ppc_altivec_vperm:
9824 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9825 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9826 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009827
Chris Lattner0521e3c2008-06-18 04:33:20 +00009828 // Check that all of the elements are integer constants or undefs.
9829 bool AllEltsOk = true;
9830 for (unsigned i = 0; i != 16; ++i) {
9831 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9832 !isa<UndefValue>(Mask->getOperand(i))) {
9833 AllEltsOk = false;
9834 break;
9835 }
9836 }
9837
9838 if (AllEltsOk) {
9839 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009840 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9841 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009842 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009843
Chris Lattner0521e3c2008-06-18 04:33:20 +00009844 // Only extract each element once.
9845 Value *ExtractedElts[32];
9846 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9847
Chris Lattnere2ed0572006-04-06 19:19:17 +00009848 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009849 if (isa<UndefValue>(Mask->getOperand(i)))
9850 continue;
9851 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9852 Idx &= 31; // Match the hardware behavior.
9853
9854 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009855 ExtractedElts[Idx] =
9856 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9857 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9858 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009859 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009860
Chris Lattner0521e3c2008-06-18 04:33:20 +00009861 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009862 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9863 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9864 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009865 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009866 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009867 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009868 }
9869 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009870
Chris Lattner0521e3c2008-06-18 04:33:20 +00009871 case Intrinsic::stackrestore: {
9872 // If the save is right next to the restore, remove the restore. This can
9873 // happen when variable allocas are DCE'd.
9874 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9875 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9876 BasicBlock::iterator BI = SS;
9877 if (&*++BI == II)
9878 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009879 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009880 }
9881
9882 // Scan down this block to see if there is another stack restore in the
9883 // same block without an intervening call/alloca.
9884 BasicBlock::iterator BI = II;
9885 TerminatorInst *TI = II->getParent()->getTerminator();
9886 bool CannotRemove = false;
9887 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009888 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009889 CannotRemove = true;
9890 break;
9891 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009892 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9893 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9894 // If there is a stackrestore below this one, remove this one.
9895 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9896 return EraseInstFromFunction(CI);
9897 // Otherwise, ignore the intrinsic.
9898 } else {
9899 // If we found a non-intrinsic call, we can't remove the stack
9900 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009901 CannotRemove = true;
9902 break;
9903 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009904 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009905 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009906
9907 // If the stack restore is in a return/unwind block and if there are no
9908 // allocas or calls between the restore and the return, nuke the restore.
9909 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9910 return EraseInstFromFunction(CI);
9911 break;
9912 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009913 }
9914
Chris Lattner8b0ea312006-01-13 20:11:04 +00009915 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009916}
9917
9918// InvokeInst simplification
9919//
9920Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009921 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009922}
9923
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009924/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9925/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009926static bool isSafeToEliminateVarargsCast(const CallSite CS,
9927 const CastInst * const CI,
9928 const TargetData * const TD,
9929 const int ix) {
9930 if (!CI->isLosslessCast())
9931 return false;
9932
9933 // The size of ByVal arguments is derived from the type, so we
9934 // can't change to a type with a different size. If the size were
9935 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009936 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009937 return true;
9938
9939 const Type* SrcTy =
9940 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9941 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9942 if (!SrcTy->isSized() || !DstTy->isSized())
9943 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009944 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009945 return false;
9946 return true;
9947}
9948
Chris Lattnera44d8a22003-10-07 22:32:43 +00009949// visitCallSite - Improvements for call and invoke instructions.
9950//
9951Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009952 bool Changed = false;
9953
9954 // If the callee is a constexpr cast of a function, attempt to move the cast
9955 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009956 if (transformConstExprCastCall(CS)) return 0;
9957
Chris Lattner6c266db2003-10-07 22:54:13 +00009958 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009959
Chris Lattner08b22ec2005-05-13 07:09:09 +00009960 if (Function *CalleeF = dyn_cast<Function>(Callee))
9961 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9962 Instruction *OldCall = CS.getInstruction();
9963 // If the call and callee calling conventions don't match, this call must
9964 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009965 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009966 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +00009967 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009968 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009969 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009970 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9971 return EraseInstFromFunction(*OldCall);
9972 return 0;
9973 }
9974
Chris Lattner17be6352004-10-18 02:59:09 +00009975 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9976 // This instruction is not reachable, just remove it. We insert a store to
9977 // undef so that we know that this code is not reachable, despite the fact
9978 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009979 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009980 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +00009981 CS.getInstruction());
9982
9983 if (!CS.getInstruction()->use_empty())
9984 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009985 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009986
9987 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9988 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009989 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009990 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009991 }
Chris Lattner17be6352004-10-18 02:59:09 +00009992 return EraseInstFromFunction(*CS.getInstruction());
9993 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009994
Duncan Sandscdb6d922007-09-17 10:26:40 +00009995 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9996 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9997 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9998 return transformCallThroughTrampoline(CS);
9999
Chris Lattner6c266db2003-10-07 22:54:13 +000010000 const PointerType *PTy = cast<PointerType>(Callee->getType());
10001 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10002 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010003 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010004 // See if we can optimize any arguments passed through the varargs area of
10005 // the call.
10006 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010007 E = CS.arg_end(); I != E; ++I, ++ix) {
10008 CastInst *CI = dyn_cast<CastInst>(*I);
10009 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10010 *I = CI->getOperand(0);
10011 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010012 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010013 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010014 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010015
Duncan Sandsf0c33542007-12-19 21:13:37 +000010016 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010017 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010018 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010019 Changed = true;
10020 }
10021
Chris Lattner6c266db2003-10-07 22:54:13 +000010022 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010023}
10024
Chris Lattner9fe38862003-06-19 17:00:31 +000010025// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10026// attempt to move the cast to the arguments of the call/invoke.
10027//
10028bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10029 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10030 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010031 if (CE->getOpcode() != Instruction::BitCast ||
10032 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010033 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010034 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010035 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010036 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010037
10038 // Okay, this is a cast from a function to a different type. Unless doing so
10039 // would cause a type conversion of one of our arguments, change this call to
10040 // be a direct call with arguments casted to the appropriate types.
10041 //
10042 const FunctionType *FT = Callee->getFunctionType();
10043 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010044 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010045
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010046 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010047 return false; // TODO: Handle multiple return values.
10048
Chris Lattnerf78616b2004-01-14 06:06:08 +000010049 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010050 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010051 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010052 // Conversion is ok if changing from one pointer type to another or from
10053 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010054 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010055 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010056 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010057 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010058 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010059
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010060 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010061 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010062 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010063 return false; // Cannot transform this return value.
10064
Chris Lattner58d74912008-03-12 17:45:29 +000010065 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010066 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010067 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010068 return false; // Attribute not compatible with transformed value.
10069 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010070
Chris Lattnerf78616b2004-01-14 06:06:08 +000010071 // If the callsite is an invoke instruction, and the return value is used by
10072 // a PHI node in a successor, we cannot change the return type of the call
10073 // because there is no place to put the cast instruction (without breaking
10074 // the critical edge). Bail out in this case.
10075 if (!Caller->use_empty())
10076 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10077 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10078 UI != E; ++UI)
10079 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10080 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010081 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010082 return false;
10083 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010084
10085 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10086 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010087
Chris Lattner9fe38862003-06-19 17:00:31 +000010088 CallSite::arg_iterator AI = CS.arg_begin();
10089 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10090 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010091 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010092
10093 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010094 return false; // Cannot transform this parameter value.
10095
Devang Patel19c87462008-09-26 22:53:05 +000010096 if (CallerPAL.getParamAttributes(i + 1)
10097 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010098 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010099
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010100 // Converting from one pointer type to another or between a pointer and an
10101 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010102 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010103 (TD && ((isa<PointerType>(ParamTy) ||
10104 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10105 (isa<PointerType>(ActTy) ||
10106 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010107 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010108 }
10109
10110 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010111 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010112 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010113
Chris Lattner58d74912008-03-12 17:45:29 +000010114 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10115 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010116 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010117 // won't be dropping them. Check that these extra arguments have attributes
10118 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010119 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10120 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010121 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010122 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010123 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010124 return false;
10125 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010126
Chris Lattner9fe38862003-06-19 17:00:31 +000010127 // Okay, we decided that this is a safe thing to do: go ahead and start
10128 // inserting cast instructions as necessary...
10129 std::vector<Value*> Args;
10130 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010131 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010132 attrVec.reserve(NumCommonArgs);
10133
10134 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010135 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010136
10137 // If the return value is not being used, the type may not be compatible
10138 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010139 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010140
10141 // Add the new return attributes.
10142 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010143 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010144
10145 AI = CS.arg_begin();
10146 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10147 const Type *ParamTy = FT->getParamType(i);
10148 if ((*AI)->getType() == ParamTy) {
10149 Args.push_back(*AI);
10150 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010151 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010152 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010153 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010154 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010155
10156 // 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));
Chris Lattner9fe38862003-06-19 17:00:31 +000010159 }
10160
10161 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010162 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010163 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010164 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010165
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010166 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010167 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010168 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010169 errs() << "WARNING: While resolving call to function '"
10170 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010171 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010172 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010173 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10174 const Type *PTy = getPromotedType((*AI)->getType());
10175 if (PTy != (*AI)->getType()) {
10176 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010177 Instruction::CastOps opcode =
10178 CastInst::getCastOpcode(*AI, false, PTy, false);
10179 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010180 } else {
10181 Args.push_back(*AI);
10182 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010183
Duncan Sandse1e520f2008-01-13 08:02:44 +000010184 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010185 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010186 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010187 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010188 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010189 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010190
Devang Patel19c87462008-09-26 22:53:05 +000010191 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10192 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10193
Owen Anderson1d0be152009-08-13 21:58:54 +000010194 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010195 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010196
Eric Christophera66297a2009-07-25 02:45:27 +000010197 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10198 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010199
Chris Lattner9fe38862003-06-19 17:00:31 +000010200 Instruction *NC;
10201 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010202 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010203 Args.begin(), Args.end(),
10204 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010205 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010206 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010207 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010208 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10209 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010210 CallInst *CI = cast<CallInst>(Caller);
10211 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010212 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010213 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010214 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010215 }
10216
Chris Lattner6934a042007-02-11 01:23:03 +000010217 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010218 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010219 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010220 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010221 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010222 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010223 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010224
10225 // If this is an invoke instruction, we should insert it after the first
10226 // non-phi, instruction in the normal successor block.
10227 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010228 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010229 InsertNewInstBefore(NC, *I);
10230 } else {
10231 // Otherwise, it's a call, just insert cast right after the call instr
10232 InsertNewInstBefore(NC, *Caller);
10233 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010234 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010235 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010236 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010237 }
10238 }
10239
Chris Lattner931f8f32009-08-31 05:17:58 +000010240
10241 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010242 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010243
10244 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010245 return true;
10246}
10247
Duncan Sandscdb6d922007-09-17 10:26:40 +000010248// transformCallThroughTrampoline - Turn a call to a function created by the
10249// init_trampoline intrinsic into a direct call to the underlying function.
10250//
10251Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10252 Value *Callee = CS.getCalledValue();
10253 const PointerType *PTy = cast<PointerType>(Callee->getType());
10254 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010255 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010256
10257 // If the call already has the 'nest' attribute somewhere then give up -
10258 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010259 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010260 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010261
10262 IntrinsicInst *Tramp =
10263 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10264
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010265 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010266 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10267 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10268
Devang Patel05988662008-09-25 21:00:45 +000010269 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010270 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010271 unsigned NestIdx = 1;
10272 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010273 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010274
10275 // Look for a parameter marked with the 'nest' attribute.
10276 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10277 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010278 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010279 // Record the parameter type and any other attributes.
10280 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010281 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010282 break;
10283 }
10284
10285 if (NestTy) {
10286 Instruction *Caller = CS.getInstruction();
10287 std::vector<Value*> NewArgs;
10288 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10289
Devang Patel05988662008-09-25 21:00:45 +000010290 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010291 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010292
Duncan Sandscdb6d922007-09-17 10:26:40 +000010293 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010294 // mean appending it. Likewise for attributes.
10295
Devang Patel19c87462008-09-26 22:53:05 +000010296 // Add any result attributes.
10297 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010298 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010299
Duncan Sandscdb6d922007-09-17 10:26:40 +000010300 {
10301 unsigned Idx = 1;
10302 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10303 do {
10304 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010305 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010306 Value *NestVal = Tramp->getOperand(3);
10307 if (NestVal->getType() != NestTy)
10308 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10309 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010310 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010311 }
10312
10313 if (I == E)
10314 break;
10315
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010316 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010317 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010318 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010319 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010320 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010321
10322 ++Idx, ++I;
10323 } while (1);
10324 }
10325
Devang Patel19c87462008-09-26 22:53:05 +000010326 // Add any function attributes.
10327 if (Attributes Attr = Attrs.getFnAttributes())
10328 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10329
Duncan Sandscdb6d922007-09-17 10:26:40 +000010330 // The trampoline may have been bitcast to a bogus type (FTy).
10331 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010332 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010333
Duncan Sandscdb6d922007-09-17 10:26:40 +000010334 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010335 NewTypes.reserve(FTy->getNumParams()+1);
10336
Duncan Sandscdb6d922007-09-17 10:26:40 +000010337 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010338 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010339 {
10340 unsigned Idx = 1;
10341 FunctionType::param_iterator I = FTy->param_begin(),
10342 E = FTy->param_end();
10343
10344 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010345 if (Idx == NestIdx)
10346 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010347 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010348
10349 if (I == E)
10350 break;
10351
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010352 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010354
10355 ++Idx, ++I;
10356 } while (1);
10357 }
10358
10359 // Replace the trampoline call with a direct call. Let the generic
10360 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010361 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010362 FTy->isVarArg());
10363 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010364 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010365 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010366 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010367 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10368 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369
10370 Instruction *NewCaller;
10371 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010372 NewCaller = InvokeInst::Create(NewCallee,
10373 II->getNormalDest(), II->getUnwindDest(),
10374 NewArgs.begin(), NewArgs.end(),
10375 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010377 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010379 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10380 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010381 if (cast<CallInst>(Caller)->isTailCall())
10382 cast<CallInst>(NewCaller)->setTailCall();
10383 cast<CallInst>(NewCaller)->
10384 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010385 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010387 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010388 Caller->replaceAllUsesWith(NewCaller);
10389 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010390 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391 return 0;
10392 }
10393 }
10394
10395 // Replace the trampoline call with a direct call. Since there is no 'nest'
10396 // parameter, there is no need to adjust the argument list. Let the generic
10397 // code sort out any function type mismatches.
10398 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010399 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010400 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010401 CS.setCalledFunction(NewCallee);
10402 return CS.getInstruction();
10403}
10404
Dan Gohman9ad29202009-09-16 16:50:24 +000010405/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10406/// 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 +000010407/// and a single binop.
10408Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10409 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010410 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010411 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010412 Value *LHSVal = FirstInst->getOperand(0);
10413 Value *RHSVal = FirstInst->getOperand(1);
10414
10415 const Type *LHSType = LHSVal->getType();
10416 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010417
Dan Gohman9ad29202009-09-16 16:50:24 +000010418 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010419 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010420 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010421 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010422 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010423 // types or GEP's with different index types.
10424 I->getOperand(0)->getType() != LHSType ||
10425 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010426 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010427
10428 // If they are CmpInst instructions, check their predicates
10429 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10430 if (cast<CmpInst>(I)->getPredicate() !=
10431 cast<CmpInst>(FirstInst)->getPredicate())
10432 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010433
10434 // Keep track of which operand needs a phi node.
10435 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10436 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010437 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010438
10439 // If both LHS and RHS would need a PHI, don't do this transformation,
10440 // because it would increase the number of PHIs entering the block,
10441 // which leads to higher register pressure. This is especially
10442 // bad when the PHIs are in the header of a loop.
10443 if (!LHSVal && !RHSVal)
10444 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010445
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010446 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010447
Chris Lattner7da52b22006-11-01 04:51:18 +000010448 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010449 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010450 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010451 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010452 NewLHS = PHINode::Create(LHSType,
10453 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010454 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10455 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010456 InsertNewInstBefore(NewLHS, PN);
10457 LHSVal = NewLHS;
10458 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010459
10460 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010461 NewRHS = PHINode::Create(RHSType,
10462 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010463 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10464 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010465 InsertNewInstBefore(NewRHS, PN);
10466 RHSVal = NewRHS;
10467 }
10468
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010469 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010470 if (NewLHS || NewRHS) {
10471 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10472 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10473 if (NewLHS) {
10474 Value *NewInLHS = InInst->getOperand(0);
10475 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10476 }
10477 if (NewRHS) {
10478 Value *NewInRHS = InInst->getOperand(1);
10479 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10480 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010481 }
10482 }
10483
Chris Lattner7da52b22006-11-01 04:51:18 +000010484 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010485 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010486 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010487 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010488 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010489}
10490
Chris Lattner05f18922008-12-01 02:34:36 +000010491Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10492 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10493
10494 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10495 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010496 // This is true if all GEP bases are allocas and if all indices into them are
10497 // constants.
10498 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010499
10500 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010501 // more than one phi, which leads to higher register pressure. This is
10502 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010503 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010504
Dan Gohman9ad29202009-09-16 16:50:24 +000010505 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010506 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10507 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10508 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10509 GEP->getNumOperands() != FirstInst->getNumOperands())
10510 return 0;
10511
Chris Lattner36d3e322009-02-21 00:46:50 +000010512 // Keep track of whether or not all GEPs are of alloca pointers.
10513 if (AllBasePointersAreAllocas &&
10514 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10515 !GEP->hasAllConstantIndices()))
10516 AllBasePointersAreAllocas = false;
10517
Chris Lattner05f18922008-12-01 02:34:36 +000010518 // Compare the operand lists.
10519 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10520 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10521 continue;
10522
10523 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10524 // if one of the PHIs has a constant for the index. The index may be
10525 // substantially cheaper to compute for the constants, so making it a
10526 // variable index could pessimize the path. This also handles the case
10527 // for struct indices, which must always be constant.
10528 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10529 isa<ConstantInt>(GEP->getOperand(op)))
10530 return 0;
10531
10532 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10533 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010534
10535 // If we already needed a PHI for an earlier operand, and another operand
10536 // also requires a PHI, we'd be introducing more PHIs than we're
10537 // eliminating, which increases register pressure on entry to the PHI's
10538 // block.
10539 if (NeededPhi)
10540 return 0;
10541
Chris Lattner05f18922008-12-01 02:34:36 +000010542 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010543 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010544 }
10545 }
10546
Chris Lattner36d3e322009-02-21 00:46:50 +000010547 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010548 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010549 // offset calculation, but all the predecessors will have to materialize the
10550 // stack address into a register anyway. We'd actually rather *clone* the
10551 // load up into the predecessors so that we have a load of a gep of an alloca,
10552 // which can usually all be folded into the load.
10553 if (AllBasePointersAreAllocas)
10554 return 0;
10555
Chris Lattner05f18922008-12-01 02:34:36 +000010556 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10557 // that is variable.
10558 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10559
10560 bool HasAnyPHIs = false;
10561 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10562 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10563 Value *FirstOp = FirstInst->getOperand(i);
10564 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10565 FirstOp->getName()+".pn");
10566 InsertNewInstBefore(NewPN, PN);
10567
10568 NewPN->reserveOperandSpace(e);
10569 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10570 OperandPhis[i] = NewPN;
10571 FixedOperands[i] = NewPN;
10572 HasAnyPHIs = true;
10573 }
10574
10575
10576 // Add all operands to the new PHIs.
10577 if (HasAnyPHIs) {
10578 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10579 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10580 BasicBlock *InBB = PN.getIncomingBlock(i);
10581
10582 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10583 if (PHINode *OpPhi = OperandPhis[op])
10584 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10585 }
10586 }
10587
10588 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010589 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10590 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10591 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010592 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10593 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010594}
10595
10596
Chris Lattner21550882009-02-23 05:56:17 +000010597/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10598/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010599/// obvious the value of the load is not changed from the point of the load to
10600/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010601///
10602/// Finally, it is safe, but not profitable, to sink a load targetting a
10603/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10604/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010605static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010606 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10607
10608 for (++BBI; BBI != E; ++BBI)
10609 if (BBI->mayWriteToMemory())
10610 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010611
10612 // Check for non-address taken alloca. If not address-taken already, it isn't
10613 // profitable to do this xform.
10614 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10615 bool isAddressTaken = false;
10616 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10617 UI != E; ++UI) {
10618 if (isa<LoadInst>(UI)) continue;
10619 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10620 // If storing TO the alloca, then the address isn't taken.
10621 if (SI->getOperand(1) == AI) continue;
10622 }
10623 isAddressTaken = true;
10624 break;
10625 }
10626
Chris Lattner36d3e322009-02-21 00:46:50 +000010627 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010628 return false;
10629 }
10630
Chris Lattner36d3e322009-02-21 00:46:50 +000010631 // If this load is a load from a GEP with a constant offset from an alloca,
10632 // then we don't want to sink it. In its present form, it will be
10633 // load [constant stack offset]. Sinking it will cause us to have to
10634 // materialize the stack addresses in each predecessor in a register only to
10635 // do a shared load from register in the successor.
10636 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10637 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10638 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10639 return false;
10640
Chris Lattner76c73142006-11-01 07:13:54 +000010641 return true;
10642}
10643
Chris Lattner9fe38862003-06-19 17:00:31 +000010644
Chris Lattnerbac32862004-11-14 19:13:23 +000010645// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10646// operator and they all are only used by the PHI, PHI together their
10647// inputs, and do the operation once, to the result of the PHI.
10648Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10649 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10650
10651 // Scan the instruction, looking for input operations that can be folded away.
10652 // If all input operands to the phi are the same instruction (e.g. a cast from
10653 // the same type or "+42") we can pull the operation through the PHI, reducing
10654 // code size and simplifying code.
10655 Constant *ConstantOp = 0;
10656 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010657 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010658 if (isa<CastInst>(FirstInst)) {
10659 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010660 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010661 // Can fold binop, compare or shift here if the RHS is a constant,
10662 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010663 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010664 if (ConstantOp == 0)
10665 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010666 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10667 isVolatile = LI->isVolatile();
10668 // We can't sink the load if the loaded value could be modified between the
10669 // load and the PHI.
10670 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010671 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010672 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010673
10674 // If the PHI is of volatile loads and the load block has multiple
10675 // successors, sinking it would remove a load of the volatile value from
10676 // the path through the other successor.
10677 if (isVolatile &&
10678 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10679 return 0;
10680
Chris Lattner9c080502006-11-01 07:43:41 +000010681 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010682 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010683 } else {
10684 return 0; // Cannot fold this operation.
10685 }
10686
10687 // Check to see if all arguments are the same operation.
10688 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10689 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10690 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010691 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010692 return 0;
10693 if (CastSrcTy) {
10694 if (I->getOperand(0)->getType() != CastSrcTy)
10695 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010696 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010697 // We can't sink the load if the loaded value could be modified between
10698 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010699 if (LI->isVolatile() != isVolatile ||
10700 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010701 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010702 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010703
Chris Lattner71042962008-07-08 17:18:32 +000010704 // If the PHI is of volatile loads and the load block has multiple
10705 // successors, sinking it would remove a load of the volatile value from
10706 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010707 if (isVolatile &&
10708 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10709 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010710
Chris Lattnerbac32862004-11-14 19:13:23 +000010711 } else if (I->getOperand(1) != ConstantOp) {
10712 return 0;
10713 }
10714 }
10715
10716 // Okay, they are all the same operation. Create a new PHI node of the
10717 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010718 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10719 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010720 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010721
10722 Value *InVal = FirstInst->getOperand(0);
10723 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010724
10725 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010726 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10727 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10728 if (NewInVal != InVal)
10729 InVal = 0;
10730 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10731 }
10732
10733 Value *PhiVal;
10734 if (InVal) {
10735 // The new PHI unions all of the same values together. This is really
10736 // common, so we handle it intelligently here for compile-time speed.
10737 PhiVal = InVal;
10738 delete NewPN;
10739 } else {
10740 InsertNewInstBefore(NewPN, PN);
10741 PhiVal = NewPN;
10742 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010743
Chris Lattnerbac32862004-11-14 19:13:23 +000010744 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010745 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010746 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010747 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010748 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010749 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010750 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010751 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010752 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10753
10754 // If this was a volatile load that we are merging, make sure to loop through
10755 // and mark all the input loads as non-volatile. If we don't do this, we will
10756 // insert a new volatile load and the old ones will not be deletable.
10757 if (isVolatile)
10758 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10759 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10760
10761 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010762}
Chris Lattnera1be5662002-05-02 17:06:02 +000010763
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010764/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10765/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010766static bool DeadPHICycle(PHINode *PN,
10767 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010768 if (PN->use_empty()) return true;
10769 if (!PN->hasOneUse()) return false;
10770
10771 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010772 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010773 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010774
10775 // Don't scan crazily complex things.
10776 if (PotentiallyDeadPHIs.size() == 16)
10777 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010778
10779 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10780 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010781
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010782 return false;
10783}
10784
Chris Lattnercf5008a2007-11-06 21:52:06 +000010785/// PHIsEqualValue - Return true if this phi node is always equal to
10786/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10787/// z = some value; x = phi (y, z); y = phi (x, z)
10788static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10789 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10790 // See if we already saw this PHI node.
10791 if (!ValueEqualPHIs.insert(PN))
10792 return true;
10793
10794 // Don't scan crazily complex things.
10795 if (ValueEqualPHIs.size() == 16)
10796 return false;
10797
10798 // Scan the operands to see if they are either phi nodes or are equal to
10799 // the value.
10800 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10801 Value *Op = PN->getIncomingValue(i);
10802 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10803 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10804 return false;
10805 } else if (Op != NonPhiInVal)
10806 return false;
10807 }
10808
10809 return true;
10810}
10811
10812
Chris Lattner473945d2002-05-06 18:06:38 +000010813// PHINode simplification
10814//
Chris Lattner7e708292002-06-25 16:13:24 +000010815Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010816 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010817 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010818
Owen Anderson7e057142006-07-10 22:03:18 +000010819 if (Value *V = PN.hasConstantValue())
10820 return ReplaceInstUsesWith(PN, V);
10821
Owen Anderson7e057142006-07-10 22:03:18 +000010822 // If all PHI operands are the same operation, pull them through the PHI,
10823 // reducing code size.
10824 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010825 isa<Instruction>(PN.getIncomingValue(1)) &&
10826 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10827 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10828 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10829 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010830 PN.getIncomingValue(0)->hasOneUse())
10831 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10832 return Result;
10833
10834 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10835 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10836 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010837 if (PN.hasOneUse()) {
10838 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10839 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010840 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010841 PotentiallyDeadPHIs.insert(&PN);
10842 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010843 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010844 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010845
10846 // If this phi has a single use, and if that use just computes a value for
10847 // the next iteration of a loop, delete the phi. This occurs with unused
10848 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10849 // common case here is good because the only other things that catch this
10850 // are induction variable analysis (sometimes) and ADCE, which is only run
10851 // late.
10852 if (PHIUser->hasOneUse() &&
10853 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10854 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010855 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010856 }
10857 }
Owen Anderson7e057142006-07-10 22:03:18 +000010858
Chris Lattnercf5008a2007-11-06 21:52:06 +000010859 // We sometimes end up with phi cycles that non-obviously end up being the
10860 // same value, for example:
10861 // z = some value; x = phi (y, z); y = phi (x, z)
10862 // where the phi nodes don't necessarily need to be in the same block. Do a
10863 // quick check to see if the PHI node only contains a single non-phi value, if
10864 // so, scan to see if the phi cycle is actually equal to that value.
10865 {
10866 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10867 // Scan for the first non-phi operand.
10868 while (InValNo != NumOperandVals &&
10869 isa<PHINode>(PN.getIncomingValue(InValNo)))
10870 ++InValNo;
10871
10872 if (InValNo != NumOperandVals) {
10873 Value *NonPhiInVal = PN.getOperand(InValNo);
10874
10875 // Scan the rest of the operands to see if there are any conflicts, if so
10876 // there is no need to recursively scan other phis.
10877 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10878 Value *OpVal = PN.getIncomingValue(InValNo);
10879 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10880 break;
10881 }
10882
10883 // If we scanned over all operands, then we have one unique value plus
10884 // phi values. Scan PHI nodes to see if they all merge in each other or
10885 // the value.
10886 if (InValNo == NumOperandVals) {
10887 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10888 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10889 return ReplaceInstUsesWith(PN, NonPhiInVal);
10890 }
10891 }
10892 }
Chris Lattner60921c92003-12-19 05:58:40 +000010893 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010894}
10895
Chris Lattner7e708292002-06-25 16:13:24 +000010896Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010897 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010898 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010899 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010900 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010901
Chris Lattnere87597f2004-10-16 18:11:37 +000010902 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010903 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010904
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010905 bool HasZeroPointerIndex = false;
10906 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10907 HasZeroPointerIndex = C->isNullValue();
10908
10909 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010910 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010911
Chris Lattner28977af2004-04-05 01:30:19 +000010912 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010913 if (TD) {
10914 bool MadeChange = false;
10915 unsigned PtrSize = TD->getPointerSizeInBits();
10916
10917 gep_type_iterator GTI = gep_type_begin(GEP);
10918 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10919 I != E; ++I, ++GTI) {
10920 if (!isa<SequentialType>(*GTI)) continue;
10921
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010922 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010923 // to what we need. If narrower, sign-extend it to what we need. This
10924 // explicit cast can make subsequent optimizations more obvious.
10925 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010926 if (OpBits == PtrSize)
10927 continue;
10928
Chris Lattner2345d1d2009-08-30 20:01:10 +000010929 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010930 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010931 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010932 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010933 }
Chris Lattner28977af2004-04-05 01:30:19 +000010934
Chris Lattner90ac28c2002-08-02 19:29:35 +000010935 // Combine Indices - If the source pointer to this getelementptr instruction
10936 // is a getelementptr instruction, combine the indices of the two
10937 // getelementptr instructions into a single instruction.
10938 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010939 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010940 // Note that if our source is a gep chain itself that we wait for that
10941 // chain to be resolved before we perform this transformation. This
10942 // avoids us creating a TON of code in some cases.
10943 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010944 if (GetElementPtrInst *SrcGEP =
10945 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10946 if (SrcGEP->getNumOperands() == 2)
10947 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010948
Chris Lattner72588fc2007-02-15 22:48:32 +000010949 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010950
10951 // Find out whether the last index in the source GEP is a sequential idx.
10952 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010953 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10954 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010955 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010956
Chris Lattner90ac28c2002-08-02 19:29:35 +000010957 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010958 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010959 // Replace: gep (gep %P, long B), long A, ...
10960 // With: T = long A+B; gep %P, T, ...
10961 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010962 Value *Sum;
10963 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10964 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010965 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010966 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010967 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010968 Sum = SO1;
10969 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010970 // If they aren't the same type, then the input hasn't been processed
10971 // by the loop above yet (which canonicalizes sequential index types to
10972 // intptr_t). Just avoid transforming this until the input has been
10973 // normalized.
10974 if (SO1->getType() != GO1->getType())
10975 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010976 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010977 }
Chris Lattner620ce142004-05-07 22:09:22 +000010978
Chris Lattnerab984842009-08-30 05:30:55 +000010979 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010980 if (Src->getNumOperands() == 2) {
10981 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010982 GEP.setOperand(1, Sum);
10983 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010984 }
Chris Lattnerab984842009-08-30 05:30:55 +000010985 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010986 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010987 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010988 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010989 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010990 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010991 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010992 Indices.append(Src->op_begin()+1, Src->op_end());
10993 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010994 }
10995
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010996 if (!Indices.empty())
10997 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10998 Src->isInBounds()) ?
10999 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11000 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011001 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011002 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011003 }
11004
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011005 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11006 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011007 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011008
Chris Lattner2de23192009-08-30 20:38:21 +000011009 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11010 // want to change the gep until the bitcasts are eliminated.
11011 if (getBitCastOperand(X)) {
11012 Worklist.AddValue(PtrOp);
11013 return 0;
11014 }
11015
Chris Lattner963f4ba2009-08-30 20:36:46 +000011016 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11017 // into : GEP [10 x i8]* X, i32 0, ...
11018 //
11019 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11020 // into : GEP i8* X, ...
11021 //
11022 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011023 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011024 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11025 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011026 if (const ArrayType *CATy =
11027 dyn_cast<ArrayType>(CPTy->getElementType())) {
11028 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11029 if (CATy->getElementType() == XTy->getElementType()) {
11030 // -> GEP i8* X, ...
11031 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011032 return cast<GEPOperator>(&GEP)->isInBounds() ?
11033 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11034 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011035 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11036 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011037 }
11038
11039 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011040 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011041 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011042 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011043 // At this point, we know that the cast source type is a pointer
11044 // to an array of the same type as the destination pointer
11045 // array. Because the array type is never stepped over (there
11046 // is a leading zero) we can fold the cast into this GEP.
11047 GEP.setOperand(0, X);
11048 return &GEP;
11049 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011050 }
11051 }
Chris Lattnereed48272005-09-13 00:40:14 +000011052 } else if (GEP.getNumOperands() == 2) {
11053 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011054 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11055 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011056 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11057 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011058 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011059 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11060 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011061 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011062 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011063 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011064 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11065 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011066 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011067 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011068 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011069 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011070
11071 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011072 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011073 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011074 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011075
Owen Anderson1d0be152009-08-13 21:58:54 +000011076 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011077 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011078 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011079
11080 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11081 // allow either a mul, shift, or constant here.
11082 Value *NewIdx = 0;
11083 ConstantInt *Scale = 0;
11084 if (ArrayEltSize == 1) {
11085 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011086 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011087 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011088 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011089 Scale = CI;
11090 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11091 if (Inst->getOpcode() == Instruction::Shl &&
11092 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011093 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11094 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011095 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011096 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011097 NewIdx = Inst->getOperand(0);
11098 } else if (Inst->getOpcode() == Instruction::Mul &&
11099 isa<ConstantInt>(Inst->getOperand(1))) {
11100 Scale = cast<ConstantInt>(Inst->getOperand(1));
11101 NewIdx = Inst->getOperand(0);
11102 }
11103 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011104
Chris Lattner7835cdd2005-09-13 18:36:04 +000011105 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011106 // out, perform the transformation. Note, we don't know whether Scale is
11107 // signed or not. We'll use unsigned version of division/modulo
11108 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011109 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011110 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011111 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011112 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011113 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011114 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11115 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011116 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011117 }
11118
11119 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011120 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011121 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011122 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011123 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11124 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11125 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011126 // The NewGEP must be pointer typed, so must the old one -> BitCast
11127 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011128 }
11129 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011130 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011131 }
Chris Lattner58407792009-01-09 04:53:57 +000011132
Chris Lattner46cd5a12009-01-09 05:44:56 +000011133 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011134 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011135 /// Y = gep X, <...constant indices...>
11136 /// into a gep of the original struct. This is important for SROA and alias
11137 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011138 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011139 if (TD &&
11140 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011141 // Determine how much the GEP moves the pointer. We are guaranteed to get
11142 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011143 ConstantInt *OffsetV =
11144 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011145 int64_t Offset = OffsetV->getSExtValue();
11146
11147 // If this GEP instruction doesn't move the pointer, just replace the GEP
11148 // with a bitcast of the real input to the dest type.
11149 if (Offset == 0) {
11150 // If the bitcast is of an allocation, and the allocation will be
11151 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011152 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11153 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011154 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11155 if (Instruction *I = visitBitCast(*BCI)) {
11156 if (I != BCI) {
11157 I->takeName(BCI);
11158 BCI->getParent()->getInstList().insert(BCI, I);
11159 ReplaceInstUsesWith(*BCI, I);
11160 }
11161 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011162 }
Chris Lattner58407792009-01-09 04:53:57 +000011163 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011164 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011165 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011166
11167 // Otherwise, if the offset is non-zero, we need to find out if there is a
11168 // field at Offset in 'A's type. If so, we can pull the cast through the
11169 // GEP.
11170 SmallVector<Value*, 8> NewIndices;
11171 const Type *InTy =
11172 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011173 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011174 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11175 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11176 NewIndices.end()) :
11177 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11178 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011179
11180 if (NGEP->getType() == GEP.getType())
11181 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011182 NGEP->takeName(&GEP);
11183 return new BitCastInst(NGEP, GEP.getType());
11184 }
Chris Lattner58407792009-01-09 04:53:57 +000011185 }
11186 }
11187
Chris Lattner8a2a3112001-12-14 16:52:21 +000011188 return 0;
11189}
11190
Chris Lattner0864acf2002-11-04 16:18:53 +000011191Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11192 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011193 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011194 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11195 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011196 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011197 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011198
11199 // Create and insert the replacement instruction...
11200 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011201 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011202 else {
11203 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011204 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011205 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011206 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011207
Chris Lattner0864acf2002-11-04 16:18:53 +000011208 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011209 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011210 //
11211 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011212 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011213
11214 // Now that I is pointing to the first non-allocation-inst in the block,
11215 // insert our getelementptr instruction...
11216 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011217 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011218 Value *Idx[2];
11219 Idx[0] = NullIdx;
11220 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011221 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11222 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011223
11224 // Now make everything use the getelementptr instead of the original
11225 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011226 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011227 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011228 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011229 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011230 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011231
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011232 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011233 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011234 // Note that we only do this for alloca's, because malloc should allocate
11235 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011236 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011237 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011238
11239 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11240 if (AI.getAlignment() == 0)
11241 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11242 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011243
Chris Lattner0864acf2002-11-04 16:18:53 +000011244 return 0;
11245}
11246
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011247Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11248 Value *Op = FI.getOperand(0);
11249
Chris Lattner17be6352004-10-18 02:59:09 +000011250 // free undef -> unreachable.
11251 if (isa<UndefValue>(Op)) {
11252 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011253 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000011254 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011255 return EraseInstFromFunction(FI);
11256 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011257
Chris Lattner6160e852004-02-28 04:57:37 +000011258 // If we have 'free null' delete the instruction. This can happen in stl code
11259 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011260 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011261 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011262
11263 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11264 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11265 FI.setOperand(0, CI->getOperand(0));
11266 return &FI;
11267 }
11268
11269 // Change free (gep X, 0,0,0,0) into free(X)
11270 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11271 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011272 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011273 FI.setOperand(0, GEPI->getOperand(0));
11274 return &FI;
11275 }
11276 }
11277
11278 // Change free(malloc) into nothing, if the malloc has a single use.
11279 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11280 if (MI->hasOneUse()) {
11281 EraseInstFromFunction(FI);
11282 return EraseInstFromFunction(*MI);
11283 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011284 if (isMalloc(Op)) {
11285 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11286 if (Op->hasOneUse() && CI->hasOneUse()) {
11287 EraseInstFromFunction(FI);
11288 EraseInstFromFunction(*CI);
11289 return EraseInstFromFunction(*cast<Instruction>(Op));
11290 }
11291 } else {
11292 // Op is a call to malloc
11293 if (Op->hasOneUse()) {
11294 EraseInstFromFunction(FI);
11295 return EraseInstFromFunction(*cast<Instruction>(Op));
11296 }
11297 }
11298 }
Chris Lattner6160e852004-02-28 04:57:37 +000011299
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011300 return 0;
11301}
11302
11303
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011304/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011305static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011306 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011307 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011308 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011309 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011310
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011311 if (TD) {
11312 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11313 // Instead of loading constant c string, use corresponding integer value
11314 // directly if string length is small enough.
11315 std::string Str;
11316 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11317 unsigned len = Str.length();
11318 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11319 unsigned numBits = Ty->getPrimitiveSizeInBits();
11320 // Replace LI with immediate integer store.
11321 if ((numBits >> 3) == len + 1) {
11322 APInt StrVal(numBits, 0);
11323 APInt SingleChar(numBits, 0);
11324 if (TD->isLittleEndian()) {
11325 for (signed i = len-1; i >= 0; i--) {
11326 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11327 StrVal = (StrVal << 8) | SingleChar;
11328 }
11329 } else {
11330 for (unsigned i = 0; i < len; i++) {
11331 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11332 StrVal = (StrVal << 8) | SingleChar;
11333 }
11334 // Append NULL at the end.
11335 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011336 StrVal = (StrVal << 8) | SingleChar;
11337 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011338 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011339 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011340 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011341 }
11342 }
11343 }
11344
Mon P Wang6753f952009-02-07 22:19:29 +000011345 const PointerType *DestTy = cast<PointerType>(CI->getType());
11346 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011347 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011348
11349 // If the address spaces don't match, don't eliminate the cast.
11350 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11351 return 0;
11352
Chris Lattnerb89e0712004-07-13 01:49:43 +000011353 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011354
Reid Spencer42230162007-01-22 05:51:25 +000011355 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011356 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011357 // If the source is an array, the code below will not succeed. Check to
11358 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11359 // constants.
11360 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11361 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11362 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011363 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011364 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011365 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011366 SrcTy = cast<PointerType>(CastOp->getType());
11367 SrcPTy = SrcTy->getElementType();
11368 }
11369
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011370 if (IC.getTargetData() &&
11371 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011372 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011373 // Do not allow turning this into a load of an integer, which is then
11374 // casted to a pointer, this pessimizes pointer analysis a lot.
11375 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011376 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11377 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011378
Chris Lattnerf9527852005-01-31 04:50:46 +000011379 // Okay, we are casting from one integer or pointer type to another of
11380 // the same size. Instead of casting the pointer before the load, cast
11381 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011382 Value *NewLoad =
11383 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011384 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011385 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011386 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011387 }
11388 }
11389 return 0;
11390}
11391
Chris Lattner833b8a42003-06-26 05:06:25 +000011392Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11393 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011394
Dan Gohman9941f742007-07-20 16:34:21 +000011395 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011396 if (TD) {
11397 unsigned KnownAlign =
11398 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11399 if (KnownAlign >
11400 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11401 LI.getAlignment()))
11402 LI.setAlignment(KnownAlign);
11403 }
Dan Gohman9941f742007-07-20 16:34:21 +000011404
Chris Lattner963f4ba2009-08-30 20:36:46 +000011405 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011406 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011407 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011408 return Res;
11409
11410 // None of the following transforms are legal for volatile loads.
11411 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011412
Dan Gohman2276a7b2008-10-15 23:19:35 +000011413 // Do really simple store-to-load forwarding and load CSE, to catch cases
11414 // where there are several consequtive memory accesses to the same location,
11415 // separated by a few arithmetic operations.
11416 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011417 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11418 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011419
Christopher Lambb15147e2007-12-29 07:56:53 +000011420 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11421 const Value *GEPI0 = GEPI->getOperand(0);
11422 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011423 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011424 // Insert a new store to null instruction before the load to indicate
11425 // that this code is not reachable. We do this instead of inserting
11426 // an unreachable instruction directly because we cannot modify the
11427 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011428 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011429 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011430 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011431 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011432 }
Chris Lattner37366c12005-05-01 04:24:53 +000011433
Chris Lattnere87597f2004-10-16 18:11:37 +000011434 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011435 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011436 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011437 if (isa<UndefValue>(C) ||
11438 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011439 // Insert a new store to null instruction before the load to indicate that
11440 // this code is not reachable. We do this instead of inserting an
11441 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011442 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011443 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011444 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011445 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011446
Chris Lattnere87597f2004-10-16 18:11:37 +000011447 // Instcombine load (constant global) into the value loaded.
11448 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011449 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011450 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011451
Chris Lattnere87597f2004-10-16 18:11:37 +000011452 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011454 if (CE->getOpcode() == Instruction::GetElementPtr) {
11455 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011456 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011457 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +000011458 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011459 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011460 if (CE->getOperand(0)->isNullValue()) {
11461 // Insert a new store to null instruction before the load to indicate
11462 // that this code is not reachable. We do this instead of inserting
11463 // an unreachable instruction directly because we cannot modify the
11464 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011465 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011466 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011467 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011468 }
11469
Reid Spencer3da59db2006-11-27 01:05:10 +000011470 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011471 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011472 return Res;
11473 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011474 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011475 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011476
11477 // If this load comes from anywhere in a constant global, and if the global
11478 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011479 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011480 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011481 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011482 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011483 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011484 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011485 }
11486 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011487
Chris Lattner37366c12005-05-01 04:24:53 +000011488 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011489 // Change select and PHI nodes to select values instead of addresses: this
11490 // helps alias analysis out a lot, allows many others simplifications, and
11491 // exposes redundancy in the code.
11492 //
11493 // Note that we cannot do the transformation unless we know that the
11494 // introduced loads cannot trap! Something like this is valid as long as
11495 // the condition is always false: load (select bool %C, int* null, int* %G),
11496 // but it would not be valid if we transformed it to load from null
11497 // unconditionally.
11498 //
11499 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11500 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011501 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11502 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011503 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11504 SI->getOperand(1)->getName()+".val");
11505 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11506 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011507 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011508 }
11509
Chris Lattner684fe212004-09-23 15:46:00 +000011510 // load (select (cond, null, P)) -> load P
11511 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11512 if (C->isNullValue()) {
11513 LI.setOperand(0, SI->getOperand(2));
11514 return &LI;
11515 }
11516
11517 // load (select (cond, P, null)) -> load P
11518 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11519 if (C->isNullValue()) {
11520 LI.setOperand(0, SI->getOperand(1));
11521 return &LI;
11522 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011523 }
11524 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011525 return 0;
11526}
11527
Reid Spencer55af2b52007-01-19 21:20:31 +000011528/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011529/// when possible. This makes it generally easy to do alias analysis and/or
11530/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011531static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11532 User *CI = cast<User>(SI.getOperand(1));
11533 Value *CastOp = CI->getOperand(0);
11534
11535 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011536 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11537 if (SrcTy == 0) return 0;
11538
11539 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011540
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011541 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11542 return 0;
11543
Chris Lattner3914f722009-01-24 01:00:13 +000011544 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11545 /// to its first element. This allows us to handle things like:
11546 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11547 /// on 32-bit hosts.
11548 SmallVector<Value*, 4> NewGEPIndices;
11549
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011550 // If the source is an array, the code below will not succeed. Check to
11551 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11552 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011553 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11554 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011555 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011556 NewGEPIndices.push_back(Zero);
11557
11558 while (1) {
11559 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011560 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011561 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011562 NewGEPIndices.push_back(Zero);
11563 SrcPTy = STy->getElementType(0);
11564 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11565 NewGEPIndices.push_back(Zero);
11566 SrcPTy = ATy->getElementType();
11567 } else {
11568 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011569 }
Chris Lattner3914f722009-01-24 01:00:13 +000011570 }
11571
Owen Andersondebcb012009-07-29 22:17:13 +000011572 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011573 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011574
11575 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11576 return 0;
11577
Chris Lattner71759c42009-01-16 20:12:52 +000011578 // If the pointers point into different address spaces or if they point to
11579 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011580 if (!IC.getTargetData() ||
11581 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011582 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011583 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11584 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011585 return 0;
11586
11587 // Okay, we are casting from one integer or pointer type to another of
11588 // the same size. Instead of casting the pointer before
11589 // the store, cast the value to be stored.
11590 Value *NewCast;
11591 Value *SIOp0 = SI.getOperand(0);
11592 Instruction::CastOps opcode = Instruction::BitCast;
11593 const Type* CastSrcTy = SIOp0->getType();
11594 const Type* CastDstTy = SrcPTy;
11595 if (isa<PointerType>(CastDstTy)) {
11596 if (CastSrcTy->isInteger())
11597 opcode = Instruction::IntToPtr;
11598 } else if (isa<IntegerType>(CastDstTy)) {
11599 if (isa<PointerType>(SIOp0->getType()))
11600 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011601 }
Chris Lattner3914f722009-01-24 01:00:13 +000011602
11603 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11604 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011605 if (!NewGEPIndices.empty())
11606 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11607 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011608
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011609 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11610 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011611 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011612}
11613
Chris Lattner4aebaee2008-11-27 08:56:30 +000011614/// equivalentAddressValues - Test if A and B will obviously have the same
11615/// value. This includes recognizing that %t0 and %t1 will have the same
11616/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011617/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011618/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011619/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011620/// %t2 = load i32* %t1
11621///
11622static bool equivalentAddressValues(Value *A, Value *B) {
11623 // Test if the values are trivially equivalent.
11624 if (A == B) return true;
11625
11626 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011627 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11628 // its only used to compare two uses within the same basic block, which
11629 // means that they'll always either have the same value or one of them
11630 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011631 if (isa<BinaryOperator>(A) ||
11632 isa<CastInst>(A) ||
11633 isa<PHINode>(A) ||
11634 isa<GetElementPtrInst>(A))
11635 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011636 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011637 return true;
11638
11639 // Otherwise they may not be equivalent.
11640 return false;
11641}
11642
Dale Johannesen4945c652009-03-03 21:26:39 +000011643// If this instruction has two uses, one of which is a llvm.dbg.declare,
11644// return the llvm.dbg.declare.
11645DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11646 if (!V->hasNUses(2))
11647 return 0;
11648 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11649 UI != E; ++UI) {
11650 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11651 return DI;
11652 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11653 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11654 return DI;
11655 }
11656 }
11657 return 0;
11658}
11659
Chris Lattner2f503e62005-01-31 05:36:43 +000011660Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11661 Value *Val = SI.getOperand(0);
11662 Value *Ptr = SI.getOperand(1);
11663
11664 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011665 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011666 ++NumCombined;
11667 return 0;
11668 }
Chris Lattner836692d2007-01-15 06:51:56 +000011669
11670 // If the RHS is an alloca with a single use, zapify the store, making the
11671 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011672 // If the RHS is an alloca with a two uses, the other one being a
11673 // llvm.dbg.declare, zapify the store and the declare, making the
11674 // alloca dead. We must do this to prevent declare's from affecting
11675 // codegen.
11676 if (!SI.isVolatile()) {
11677 if (Ptr->hasOneUse()) {
11678 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011679 EraseInstFromFunction(SI);
11680 ++NumCombined;
11681 return 0;
11682 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011683 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11684 if (isa<AllocaInst>(GEP->getOperand(0))) {
11685 if (GEP->getOperand(0)->hasOneUse()) {
11686 EraseInstFromFunction(SI);
11687 ++NumCombined;
11688 return 0;
11689 }
11690 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11691 EraseInstFromFunction(*DI);
11692 EraseInstFromFunction(SI);
11693 ++NumCombined;
11694 return 0;
11695 }
11696 }
11697 }
11698 }
11699 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11700 EraseInstFromFunction(*DI);
11701 EraseInstFromFunction(SI);
11702 ++NumCombined;
11703 return 0;
11704 }
Chris Lattner836692d2007-01-15 06:51:56 +000011705 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011706
Dan Gohman9941f742007-07-20 16:34:21 +000011707 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011708 if (TD) {
11709 unsigned KnownAlign =
11710 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11711 if (KnownAlign >
11712 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11713 SI.getAlignment()))
11714 SI.setAlignment(KnownAlign);
11715 }
Dan Gohman9941f742007-07-20 16:34:21 +000011716
Dale Johannesenacb51a32009-03-03 01:43:03 +000011717 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011718 // stores to the same location, separated by a few arithmetic operations. This
11719 // situation often occurs with bitfield accesses.
11720 BasicBlock::iterator BBI = &SI;
11721 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11722 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011723 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011724 // Don't count debug info directives, lest they affect codegen,
11725 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11726 // It is necessary for correctness to skip those that feed into a
11727 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011728 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011729 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011730 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011731 continue;
11732 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011733
11734 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11735 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011736 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11737 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011738 ++NumDeadStore;
11739 ++BBI;
11740 EraseInstFromFunction(*PrevSI);
11741 continue;
11742 }
11743 break;
11744 }
11745
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011746 // If this is a load, we have to stop. However, if the loaded value is from
11747 // the pointer we're loading and is producing the pointer we're storing,
11748 // then *this* store is dead (X = load P; store X -> P).
11749 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011750 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11751 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011752 EraseInstFromFunction(SI);
11753 ++NumCombined;
11754 return 0;
11755 }
11756 // Otherwise, this is a load from some other location. Stores before it
11757 // may not be dead.
11758 break;
11759 }
11760
Chris Lattner9ca96412006-02-08 03:25:32 +000011761 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011762 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011763 break;
11764 }
11765
11766
11767 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011768
11769 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011770 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011771 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011772 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011773 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011774 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011775 ++NumCombined;
11776 }
11777 return 0; // Do not modify these!
11778 }
11779
11780 // store undef, Ptr -> noop
11781 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011782 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011783 ++NumCombined;
11784 return 0;
11785 }
11786
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011787 // If the pointer destination is a cast, see if we can fold the cast into the
11788 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011789 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011790 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11791 return Res;
11792 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011793 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011794 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11795 return Res;
11796
Chris Lattner408902b2005-09-12 23:23:25 +000011797
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011798 // If this store is the last instruction in the basic block (possibly
11799 // excepting debug info instructions and the pointer bitcasts that feed
11800 // into them), and if the block ends with an unconditional branch, try
11801 // to move it to the successor block.
11802 BBI = &SI;
11803 do {
11804 ++BBI;
11805 } while (isa<DbgInfoIntrinsic>(BBI) ||
11806 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011807 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011808 if (BI->isUnconditional())
11809 if (SimplifyStoreAtEndOfBlock(SI))
11810 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011811
Chris Lattner2f503e62005-01-31 05:36:43 +000011812 return 0;
11813}
11814
Chris Lattner3284d1f2007-04-15 00:07:55 +000011815/// SimplifyStoreAtEndOfBlock - Turn things like:
11816/// if () { *P = v1; } else { *P = v2 }
11817/// into a phi node with a store in the successor.
11818///
Chris Lattner31755a02007-04-15 01:02:18 +000011819/// Simplify things like:
11820/// *P = v1; if () { *P = v2; }
11821/// into a phi node with a store in the successor.
11822///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011823bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11824 BasicBlock *StoreBB = SI.getParent();
11825
11826 // Check to see if the successor block has exactly two incoming edges. If
11827 // so, see if the other predecessor contains a store to the same location.
11828 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011829 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011830
11831 // Determine whether Dest has exactly two predecessors and, if so, compute
11832 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011833 pred_iterator PI = pred_begin(DestBB);
11834 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011835 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011836 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011837 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011838 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011839 return false;
11840
11841 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011842 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011843 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011844 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011845 }
Chris Lattner31755a02007-04-15 01:02:18 +000011846 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011847 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011848
11849 // Bail out if all the relevant blocks aren't distinct (this can happen,
11850 // for example, if SI is in an infinite loop)
11851 if (StoreBB == DestBB || OtherBB == DestBB)
11852 return false;
11853
Chris Lattner31755a02007-04-15 01:02:18 +000011854 // Verify that the other block ends in a branch and is not otherwise empty.
11855 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011856 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011857 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011858 return false;
11859
Chris Lattner31755a02007-04-15 01:02:18 +000011860 // If the other block ends in an unconditional branch, check for the 'if then
11861 // else' case. there is an instruction before the branch.
11862 StoreInst *OtherStore = 0;
11863 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011864 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011865 // Skip over debugging info.
11866 while (isa<DbgInfoIntrinsic>(BBI) ||
11867 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11868 if (BBI==OtherBB->begin())
11869 return false;
11870 --BBI;
11871 }
11872 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011873 OtherStore = dyn_cast<StoreInst>(BBI);
11874 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11875 return false;
11876 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011877 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011878 // destinations is StoreBB, then we have the if/then case.
11879 if (OtherBr->getSuccessor(0) != StoreBB &&
11880 OtherBr->getSuccessor(1) != StoreBB)
11881 return false;
11882
11883 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011884 // if/then triangle. See if there is a store to the same ptr as SI that
11885 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011886 for (;; --BBI) {
11887 // Check to see if we find the matching store.
11888 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11889 if (OtherStore->getOperand(1) != SI.getOperand(1))
11890 return false;
11891 break;
11892 }
Eli Friedman6903a242008-06-13 22:02:12 +000011893 // If we find something that may be using or overwriting the stored
11894 // value, or if we run out of instructions, we can't do the xform.
11895 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011896 BBI == OtherBB->begin())
11897 return false;
11898 }
11899
11900 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011901 // make sure nothing reads or overwrites the stored value in
11902 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011903 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11904 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011905 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011906 return false;
11907 }
11908 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011909
Chris Lattner31755a02007-04-15 01:02:18 +000011910 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011911 Value *MergedVal = OtherStore->getOperand(0);
11912 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011913 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011914 PN->reserveOperandSpace(2);
11915 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011916 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11917 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011918 }
11919
11920 // Advance to a place where it is safe to insert the new store and
11921 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011922 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011923 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11924 OtherStore->isVolatile()), *BBI);
11925
11926 // Nuke the old stores.
11927 EraseInstFromFunction(SI);
11928 EraseInstFromFunction(*OtherStore);
11929 ++NumCombined;
11930 return true;
11931}
11932
Chris Lattner2f503e62005-01-31 05:36:43 +000011933
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011934Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11935 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011936 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011937 BasicBlock *TrueDest;
11938 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011939 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011940 !isa<Constant>(X)) {
11941 // Swap Destinations and condition...
11942 BI.setCondition(X);
11943 BI.setSuccessor(0, FalseDest);
11944 BI.setSuccessor(1, TrueDest);
11945 return &BI;
11946 }
11947
Reid Spencere4d87aa2006-12-23 06:05:41 +000011948 // Cannonicalize fcmp_one -> fcmp_oeq
11949 FCmpInst::Predicate FPred; Value *Y;
11950 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011951 TrueDest, FalseDest)) &&
11952 BI.getCondition()->hasOneUse())
11953 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11954 FPred == FCmpInst::FCMP_OGE) {
11955 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11956 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11957
11958 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011959 BI.setSuccessor(0, FalseDest);
11960 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011961 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011962 return &BI;
11963 }
11964
11965 // Cannonicalize icmp_ne -> icmp_eq
11966 ICmpInst::Predicate IPred;
11967 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011968 TrueDest, FalseDest)) &&
11969 BI.getCondition()->hasOneUse())
11970 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11971 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11972 IPred == ICmpInst::ICMP_SGE) {
11973 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11974 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11975 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011976 BI.setSuccessor(0, FalseDest);
11977 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011978 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011979 return &BI;
11980 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011981
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011982 return 0;
11983}
Chris Lattner0864acf2002-11-04 16:18:53 +000011984
Chris Lattner46238a62004-07-03 00:26:11 +000011985Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11986 Value *Cond = SI.getCondition();
11987 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11988 if (I->getOpcode() == Instruction::Add)
11989 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11990 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11991 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011992 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011993 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011994 AddRHS));
11995 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011996 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011997 return &SI;
11998 }
11999 }
12000 return 0;
12001}
12002
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012003Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012004 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012005
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012006 if (!EV.hasIndices())
12007 return ReplaceInstUsesWith(EV, Agg);
12008
12009 if (Constant *C = dyn_cast<Constant>(Agg)) {
12010 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012011 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012012
12013 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012014 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012015
12016 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12017 // Extract the element indexed by the first index out of the constant
12018 Value *V = C->getOperand(*EV.idx_begin());
12019 if (EV.getNumIndices() > 1)
12020 // Extract the remaining indices out of the constant indexed by the
12021 // first index
12022 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12023 else
12024 return ReplaceInstUsesWith(EV, V);
12025 }
12026 return 0; // Can't handle other constants
12027 }
12028 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12029 // We're extracting from an insertvalue instruction, compare the indices
12030 const unsigned *exti, *exte, *insi, *inse;
12031 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12032 exte = EV.idx_end(), inse = IV->idx_end();
12033 exti != exte && insi != inse;
12034 ++exti, ++insi) {
12035 if (*insi != *exti)
12036 // The insert and extract both reference distinctly different elements.
12037 // This means the extract is not influenced by the insert, and we can
12038 // replace the aggregate operand of the extract with the aggregate
12039 // operand of the insert. i.e., replace
12040 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12041 // %E = extractvalue { i32, { i32 } } %I, 0
12042 // with
12043 // %E = extractvalue { i32, { i32 } } %A, 0
12044 return ExtractValueInst::Create(IV->getAggregateOperand(),
12045 EV.idx_begin(), EV.idx_end());
12046 }
12047 if (exti == exte && insi == inse)
12048 // Both iterators are at the end: Index lists are identical. Replace
12049 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12050 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12051 // with "i32 42"
12052 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12053 if (exti == exte) {
12054 // The extract list is a prefix of the insert list. i.e. replace
12055 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12056 // %E = extractvalue { i32, { i32 } } %I, 1
12057 // with
12058 // %X = extractvalue { i32, { i32 } } %A, 1
12059 // %E = insertvalue { i32 } %X, i32 42, 0
12060 // by switching the order of the insert and extract (though the
12061 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012062 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12063 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012064 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12065 insi, inse);
12066 }
12067 if (insi == inse)
12068 // The insert list is a prefix of the extract list
12069 // We can simply remove the common indices from the extract and make it
12070 // operate on the inserted value instead of the insertvalue result.
12071 // i.e., replace
12072 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12073 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12074 // with
12075 // %E extractvalue { i32 } { i32 42 }, 0
12076 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12077 exti, exte);
12078 }
12079 // Can't simplify extracts from other values. Note that nested extracts are
12080 // already simplified implicitely by the above (extract ( extract (insert) )
12081 // will be translated into extract ( insert ( extract ) ) first and then just
12082 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012083 return 0;
12084}
12085
Chris Lattner220b0cf2006-03-05 00:22:33 +000012086/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12087/// is to leave as a vector operation.
12088static bool CheapToScalarize(Value *V, bool isConstant) {
12089 if (isa<ConstantAggregateZero>(V))
12090 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012091 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012092 if (isConstant) return true;
12093 // If all elts are the same, we can extract.
12094 Constant *Op0 = C->getOperand(0);
12095 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12096 if (C->getOperand(i) != Op0)
12097 return false;
12098 return true;
12099 }
12100 Instruction *I = dyn_cast<Instruction>(V);
12101 if (!I) return false;
12102
12103 // Insert element gets simplified to the inserted element or is deleted if
12104 // this is constant idx extract element and its a constant idx insertelt.
12105 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12106 isa<ConstantInt>(I->getOperand(2)))
12107 return true;
12108 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12109 return true;
12110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12111 if (BO->hasOneUse() &&
12112 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12113 CheapToScalarize(BO->getOperand(1), isConstant)))
12114 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012115 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12116 if (CI->hasOneUse() &&
12117 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12118 CheapToScalarize(CI->getOperand(1), isConstant)))
12119 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012120
12121 return false;
12122}
12123
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012124/// Read and decode a shufflevector mask.
12125///
12126/// It turns undef elements into values that are larger than the number of
12127/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012128static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12129 unsigned NElts = SVI->getType()->getNumElements();
12130 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12131 return std::vector<unsigned>(NElts, 0);
12132 if (isa<UndefValue>(SVI->getOperand(2)))
12133 return std::vector<unsigned>(NElts, 2*NElts);
12134
12135 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012136 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012137 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12138 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012139 Result.push_back(NElts*2); // undef -> 8
12140 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012141 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012142 return Result;
12143}
12144
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012145/// FindScalarElement - Given a vector and an element number, see if the scalar
12146/// value is already around as a register, for example if it were inserted then
12147/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012148static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012149 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012150 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12151 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012152 unsigned Width = PTy->getNumElements();
12153 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012154 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012155
12156 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012157 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012158 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012159 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012160 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012161 return CP->getOperand(EltNo);
12162 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12163 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012164 if (!isa<ConstantInt>(III->getOperand(2)))
12165 return 0;
12166 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012167
12168 // If this is an insert to the element we are looking for, return the
12169 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012170 if (EltNo == IIElt)
12171 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012172
12173 // Otherwise, the insertelement doesn't modify the value, recurse on its
12174 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012175 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012176 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012177 unsigned LHSWidth =
12178 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012179 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012180 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012181 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012182 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012183 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012184 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012185 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012186 }
12187
12188 // Otherwise, we don't know.
12189 return 0;
12190}
12191
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012192Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012193 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012194 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012195 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012196
Dan Gohman07a96762007-07-16 14:29:03 +000012197 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012198 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012199 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012200
Reid Spencer9d6565a2007-02-15 02:26:10 +000012201 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012202 // If vector val is constant with all elements the same, replace EI with
12203 // that element. When the elements are not identical, we cannot replace yet
12204 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012205 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012206 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012207 if (C->getOperand(i) != op0) {
12208 op0 = 0;
12209 break;
12210 }
12211 if (op0)
12212 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012213 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012214
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012215 // If extracting a specified index from the vector, see if we can recursively
12216 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012217 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012218 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012219 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012220
12221 // If this is extracting an invalid index, turn this into undef, to avoid
12222 // crashing the code below.
12223 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012224 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012225
Chris Lattner867b99f2006-10-05 06:55:50 +000012226 // This instruction only demands the single element from the input vector.
12227 // If the input vector has a single use, simplify it based on this use
12228 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012229 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012230 APInt UndefElts(VectorWidth, 0);
12231 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012232 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012233 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012234 EI.setOperand(0, V);
12235 return &EI;
12236 }
12237 }
12238
Owen Andersond672ecb2009-07-03 00:17:18 +000012239 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012240 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012241
12242 // If the this extractelement is directly using a bitcast from a vector of
12243 // the same number of elements, see if we can find the source element from
12244 // it. In this case, we will end up needing to bitcast the scalars.
12245 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12246 if (const VectorType *VT =
12247 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12248 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012249 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12250 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012251 return new BitCastInst(Elt, EI.getType());
12252 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012253 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012254
Chris Lattner73fa49d2006-05-25 22:53:38 +000012255 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012256 // Push extractelement into predecessor operation if legal and
12257 // profitable to do so
12258 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12259 if (I->hasOneUse() &&
12260 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12261 Value *newEI0 =
12262 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12263 EI.getName()+".lhs");
12264 Value *newEI1 =
12265 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12266 EI.getName()+".rhs");
12267 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012268 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012269 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012270 // Extracting the inserted element?
12271 if (IE->getOperand(2) == EI.getOperand(1))
12272 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12273 // If the inserted and extracted elements are constants, they must not
12274 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012275 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012276 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012277 EI.setOperand(0, IE->getOperand(0));
12278 return &EI;
12279 }
12280 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12281 // If this is extracting an element from a shufflevector, figure out where
12282 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012283 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12284 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012285 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012286 unsigned LHSWidth =
12287 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12288
12289 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012290 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012291 else if (SrcIdx < LHSWidth*2) {
12292 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012293 Src = SVI->getOperand(1);
12294 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012295 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012296 }
Eric Christophera3500da2009-07-25 02:28:41 +000012297 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012298 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12299 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012300 }
12301 }
Eli Friedman2451a642009-07-18 23:06:53 +000012302 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012303 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012304 return 0;
12305}
12306
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012307/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12308/// elements from either LHS or RHS, return the shuffle mask and true.
12309/// Otherwise, return false.
12310static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012311 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012312 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012313 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12314 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012315 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012316
12317 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012318 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012319 return true;
12320 } else if (V == LHS) {
12321 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012322 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012323 return true;
12324 } else if (V == RHS) {
12325 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012326 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012327 return true;
12328 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12329 // If this is an insert of an extract from some other vector, include it.
12330 Value *VecOp = IEI->getOperand(0);
12331 Value *ScalarOp = IEI->getOperand(1);
12332 Value *IdxOp = IEI->getOperand(2);
12333
Chris Lattnerd929f062006-04-27 21:14:21 +000012334 if (!isa<ConstantInt>(IdxOp))
12335 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012336 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012337
12338 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12339 // Okay, we can handle this if the vector we are insertinting into is
12340 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012341 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012342 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012343 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012344 return true;
12345 }
12346 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12347 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012348 EI->getOperand(0)->getType() == V->getType()) {
12349 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012350 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012351
12352 // This must be extracting from either LHS or RHS.
12353 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12354 // Okay, we can handle this if the vector we are insertinting into is
12355 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012356 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012357 // If so, update the mask to reflect the inserted value.
12358 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012359 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012360 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012361 } else {
12362 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012363 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012364 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012365
12366 }
12367 return true;
12368 }
12369 }
12370 }
12371 }
12372 }
12373 // TODO: Handle shufflevector here!
12374
12375 return false;
12376}
12377
12378/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12379/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12380/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012381static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012382 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012383 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012384 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012385 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012386 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012387
12388 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012389 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012390 return V;
12391 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012392 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012393 return V;
12394 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12395 // If this is an insert of an extract from some other vector, include it.
12396 Value *VecOp = IEI->getOperand(0);
12397 Value *ScalarOp = IEI->getOperand(1);
12398 Value *IdxOp = IEI->getOperand(2);
12399
12400 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12401 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12402 EI->getOperand(0)->getType() == V->getType()) {
12403 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012404 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12405 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012406
12407 // Either the extracted from or inserted into vector must be RHSVec,
12408 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012409 if (EI->getOperand(0) == RHS || RHS == 0) {
12410 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012411 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012412 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012413 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012414 return V;
12415 }
12416
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012417 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012418 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12419 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012420 // Everything but the extracted element is replaced with the RHS.
12421 for (unsigned i = 0; i != NumElts; ++i) {
12422 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012423 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012424 }
12425 return V;
12426 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012427
12428 // If this insertelement is a chain that comes from exactly these two
12429 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012430 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12431 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012432 return EI->getOperand(0);
12433
Chris Lattnerefb47352006-04-15 01:39:45 +000012434 }
12435 }
12436 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012437 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012438
12439 // Otherwise, can't do anything fancy. Return an identity vector.
12440 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012441 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012442 return V;
12443}
12444
12445Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12446 Value *VecOp = IE.getOperand(0);
12447 Value *ScalarOp = IE.getOperand(1);
12448 Value *IdxOp = IE.getOperand(2);
12449
Chris Lattner599ded12007-04-09 01:11:16 +000012450 // Inserting an undef or into an undefined place, remove this.
12451 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12452 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012453
Chris Lattnerefb47352006-04-15 01:39:45 +000012454 // If the inserted element was extracted from some other vector, and if the
12455 // indexes are constant, try to turn this into a shufflevector operation.
12456 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12457 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12458 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012459 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012460 unsigned ExtractedIdx =
12461 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012462 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012463
12464 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12465 return ReplaceInstUsesWith(IE, VecOp);
12466
12467 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012468 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012469
12470 // If we are extracting a value from a vector, then inserting it right
12471 // back into the same place, just use the input vector.
12472 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12473 return ReplaceInstUsesWith(IE, VecOp);
12474
12475 // We could theoretically do this for ANY input. However, doing so could
12476 // turn chains of insertelement instructions into a chain of shufflevector
12477 // instructions, and right now we do not merge shufflevectors. As such,
12478 // only do this in a situation where it is clear that there is benefit.
12479 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12480 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12481 // the values of VecOp, except then one read from EIOp0.
12482 // Build a new shuffle mask.
12483 std::vector<Constant*> Mask;
12484 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012485 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012486 else {
12487 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012488 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012489 NumVectorElts));
12490 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012491 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012492 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012493 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012494 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012495 }
12496
12497 // If this insertelement isn't used by some other insertelement, turn it
12498 // (and any insertelements it points to), into one big shuffle.
12499 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12500 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012501 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012502 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012503 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012504 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012505 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012506 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012507 }
12508 }
12509 }
12510
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012511 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12512 APInt UndefElts(VWidth, 0);
12513 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12514 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12515 return &IE;
12516
Chris Lattnerefb47352006-04-15 01:39:45 +000012517 return 0;
12518}
12519
12520
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012521Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12522 Value *LHS = SVI.getOperand(0);
12523 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012524 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012525
12526 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012527
Chris Lattner867b99f2006-10-05 06:55:50 +000012528 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012529 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012530 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012531
Dan Gohman488fbfc2008-09-09 18:11:14 +000012532 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012533
12534 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12535 return 0;
12536
Evan Cheng388df622009-02-03 10:05:09 +000012537 APInt UndefElts(VWidth, 0);
12538 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12539 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012540 LHS = SVI.getOperand(0);
12541 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012542 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012543 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012544
Chris Lattner863bcff2006-05-25 23:48:38 +000012545 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12546 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12547 if (LHS == RHS || isa<UndefValue>(LHS)) {
12548 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012549 // shuffle(undef,undef,mask) -> undef.
12550 return ReplaceInstUsesWith(SVI, LHS);
12551 }
12552
Chris Lattner863bcff2006-05-25 23:48:38 +000012553 // Remap any references to RHS to use LHS.
12554 std::vector<Constant*> Elts;
12555 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012556 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012557 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012558 else {
12559 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012560 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012561 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012562 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012563 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012564 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012565 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012566 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012567 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012568 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012569 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012570 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012571 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012572 LHS = SVI.getOperand(0);
12573 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012574 MadeChange = true;
12575 }
12576
Chris Lattner7b2e27922006-05-26 00:29:06 +000012577 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012578 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012579
Chris Lattner863bcff2006-05-25 23:48:38 +000012580 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12581 if (Mask[i] >= e*2) continue; // Ignore undef values.
12582 // Is this an identity shuffle of the LHS value?
12583 isLHSID &= (Mask[i] == i);
12584
12585 // Is this an identity shuffle of the RHS value?
12586 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012587 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012588
Chris Lattner863bcff2006-05-25 23:48:38 +000012589 // Eliminate identity shuffles.
12590 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12591 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012592
Chris Lattner7b2e27922006-05-26 00:29:06 +000012593 // If the LHS is a shufflevector itself, see if we can combine it with this
12594 // one without producing an unusual shuffle. Here we are really conservative:
12595 // we are absolutely afraid of producing a shuffle mask not in the input
12596 // program, because the code gen may not be smart enough to turn a merged
12597 // shuffle into two specific shuffles: it may produce worse code. As such,
12598 // we only merge two shuffles if the result is one of the two input shuffle
12599 // masks. In this case, merging the shuffles just removes one instruction,
12600 // which we know is safe. This is good for things like turning:
12601 // (splat(splat)) -> splat.
12602 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12603 if (isa<UndefValue>(RHS)) {
12604 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12605
12606 std::vector<unsigned> NewMask;
12607 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12608 if (Mask[i] >= 2*e)
12609 NewMask.push_back(2*e);
12610 else
12611 NewMask.push_back(LHSMask[Mask[i]]);
12612
12613 // If the result mask is equal to the src shuffle or this shuffle mask, do
12614 // the replacement.
12615 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012616 unsigned LHSInNElts =
12617 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012618 std::vector<Constant*> Elts;
12619 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012620 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012621 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012622 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012623 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012624 }
12625 }
12626 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12627 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012628 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012629 }
12630 }
12631 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012632
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012633 return MadeChange ? &SVI : 0;
12634}
12635
12636
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012637
Chris Lattnerea1c4542004-12-08 23:43:58 +000012638
12639/// TryToSinkInstruction - Try to move the specified instruction from its
12640/// current block into the beginning of DestBlock, which can only happen if it's
12641/// safe to move the instruction past all of the instructions between it and the
12642/// end of its block.
12643static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12644 assert(I->hasOneUse() && "Invariants didn't hold!");
12645
Chris Lattner108e9022005-10-27 17:13:11 +000012646 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012647 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012648 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012649
Chris Lattnerea1c4542004-12-08 23:43:58 +000012650 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012651 if (isa<AllocaInst>(I) && I->getParent() ==
12652 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012653 return false;
12654
Chris Lattner96a52a62004-12-09 07:14:34 +000012655 // We can only sink load instructions if there is nothing between the load and
12656 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012657 if (I->mayReadFromMemory()) {
12658 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012659 Scan != E; ++Scan)
12660 if (Scan->mayWriteToMemory())
12661 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012662 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012663
Dan Gohman02dea8b2008-05-23 21:05:58 +000012664 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012665
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012666 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012667 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012668 ++NumSunkInst;
12669 return true;
12670}
12671
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012672
12673/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12674/// all reachable code to the worklist.
12675///
12676/// This has a couple of tricks to make the code faster and more powerful. In
12677/// particular, we constant fold and DCE instructions as we go, to avoid adding
12678/// them to the worklist (this significantly speeds up instcombine on code where
12679/// many instructions are dead or constant). Additionally, if we find a branch
12680/// whose condition is a known constant, we only visit the reachable successors.
12681///
12682static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012683 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012684 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012685 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012686 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012687 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012688
Chris Lattner2c7718a2007-03-23 19:17:18 +000012689 while (!Worklist.empty()) {
12690 BB = Worklist.back();
12691 Worklist.pop_back();
12692
12693 // We have now visited this block! If we've already been here, ignore it.
12694 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012695
12696 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012697 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12698 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012699
Chris Lattner2c7718a2007-03-23 19:17:18 +000012700 // DCE instruction if trivially dead.
12701 if (isInstructionTriviallyDead(Inst)) {
12702 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012703 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012704 Inst->eraseFromParent();
12705 continue;
12706 }
12707
12708 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012709 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012710 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12711 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012712 Inst->replaceAllUsesWith(C);
12713 ++NumConstProp;
12714 Inst->eraseFromParent();
12715 continue;
12716 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012717
Devang Patel7fe1dec2008-11-19 18:56:50 +000012718 // If there are two consecutive llvm.dbg.stoppoint calls then
12719 // it is likely that the optimizer deleted code in between these
12720 // two intrinsics.
12721 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12722 if (DBI_Next) {
12723 if (DBI_Prev
12724 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12725 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012726 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012727 DBI_Prev->eraseFromParent();
12728 }
12729 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012730 } else {
12731 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012732 }
12733
Chris Lattner61488a32009-10-11 21:05:34 +000012734 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012735 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012736
12737 // Recursively visit successors. If this is a branch or switch on a
12738 // constant, only visit the reachable successor.
12739 TerminatorInst *TI = BB->getTerminator();
12740 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12741 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12742 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012743 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012744 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012745 continue;
12746 }
12747 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12748 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12749 // See if this is an explicit destination.
12750 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12751 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012752 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012753 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012754 continue;
12755 }
12756
12757 // Otherwise it is the default destination.
12758 Worklist.push_back(SI->getSuccessor(0));
12759 continue;
12760 }
12761 }
12762
12763 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12764 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012765 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012766}
12767
Chris Lattnerec9c3582007-03-03 02:04:50 +000012768bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012769 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012770 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012771
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012772 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12773 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012774
Chris Lattnerb3d59702005-07-07 20:40:38 +000012775 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012776 // Do a depth-first traversal of the function, populate the worklist with
12777 // the reachable instructions. Ignore blocks that are not reachable. Keep
12778 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012779 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012780 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012781
Chris Lattnerb3d59702005-07-07 20:40:38 +000012782 // Do a quick scan over the function. If we find any blocks that are
12783 // unreachable, remove any instructions inside of them. This prevents
12784 // the instcombine code from having to deal with some bad special cases.
12785 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12786 if (!Visited.count(BB)) {
12787 Instruction *Term = BB->getTerminator();
12788 while (Term != BB->begin()) { // Remove instrs bottom-up
12789 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012790
Chris Lattnerbdff5482009-08-23 04:37:46 +000012791 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012792 // A debug intrinsic shouldn't force another iteration if we weren't
12793 // going to do one without it.
12794 if (!isa<DbgInfoIntrinsic>(I)) {
12795 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012796 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012797 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012798 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012799 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012800 I->eraseFromParent();
12801 }
12802 }
12803 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012804
Chris Lattner873ff012009-08-30 05:55:36 +000012805 while (!Worklist.isEmpty()) {
12806 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012807 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012808
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012809 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012810 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012811 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012812 EraseInstFromFunction(*I);
12813 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012814 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012815 continue;
12816 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012817
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012818 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012819 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012820 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012821
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012822 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012823 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012824 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012825 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012826 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012827 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012828 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012829
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012830 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012831 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012832 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12833 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012834 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12835 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012836 if (NewC != CE) {
Dan Gohmane41a1152009-10-05 16:31:55 +000012837 *i = NewC;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012838 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012839 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012840 }
12841
Chris Lattnerea1c4542004-12-08 23:43:58 +000012842 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012843 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012844 BasicBlock *BB = I->getParent();
12845 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12846 if (UserParent != BB) {
12847 bool UserIsSuccessor = false;
12848 // See if the user is one of our successors.
12849 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12850 if (*SI == UserParent) {
12851 UserIsSuccessor = true;
12852 break;
12853 }
12854
12855 // If the user is one of our immediate successors, and if that successor
12856 // only has us as a predecessors (we'd have to split the critical edge
12857 // otherwise), we can keep going.
12858 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12859 next(pred_begin(UserParent)) == pred_end(UserParent))
12860 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012861 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012862 }
12863 }
12864
Chris Lattner74381062009-08-30 07:44:24 +000012865 // Now that we have an instruction, try combining it to simplify it.
12866 Builder->SetInsertPoint(I->getParent(), I);
12867
Reid Spencera9b81012007-03-26 17:44:01 +000012868#ifndef NDEBUG
12869 std::string OrigI;
12870#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012871 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012872 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12873
Chris Lattner90ac28c2002-08-02 19:29:35 +000012874 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012875 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012876 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012877 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012878 DEBUG(errs() << "IC: Old = " << *I << '\n'
12879 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012880
Chris Lattnerf523d062004-06-09 05:08:07 +000012881 // Everything uses the new instruction now.
12882 I->replaceAllUsesWith(Result);
12883
12884 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012885 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012886 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012887
Chris Lattner6934a042007-02-11 01:23:03 +000012888 // Move the name to the new instruction first.
12889 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012890
12891 // Insert the new instruction into the basic block...
12892 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012893 BasicBlock::iterator InsertPos = I;
12894
12895 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12896 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12897 ++InsertPos;
12898
12899 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012900
Chris Lattner7a1e9242009-08-30 06:13:40 +000012901 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012902 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012903#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012904 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12905 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012906#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012907
Chris Lattner90ac28c2002-08-02 19:29:35 +000012908 // If the instruction was modified, it's possible that it is now dead.
12909 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012910 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012911 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012912 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012913 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012914 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012915 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012916 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012917 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012918 }
12919 }
12920
Chris Lattner873ff012009-08-30 05:55:36 +000012921 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012922 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012923}
12924
Chris Lattnerec9c3582007-03-03 02:04:50 +000012925
12926bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012927 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012928 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012929
Chris Lattner74381062009-08-30 07:44:24 +000012930
12931 /// Builder - This is an IRBuilder that automatically inserts new
12932 /// instructions into the worklist when they are created.
12933 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12934 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12935 InstCombineIRInserter(Worklist));
12936 Builder = &TheBuilder;
12937
Chris Lattnerec9c3582007-03-03 02:04:50 +000012938 bool EverMadeChange = false;
12939
12940 // Iterate while there is work to do.
12941 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012942 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012943 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012944
12945 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012946 return EverMadeChange;
12947}
12948
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012949FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012950 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012951}