blob: 4e7264998fd3eb620536110d68f60e6db577179b [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
1050 RHSKnownZero = KnownZeroOut;
1051 RHSKnownOne = KnownOneOut;
1052 break;
1053 }
1054 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1056 RHSKnownZero, RHSKnownOne, Depth+1) ||
1057 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001058 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001059 return I;
1060 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1061 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001062
1063 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001064 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1065 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001066 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001067
1068 // Only known if known in both the LHS and RHS.
1069 RHSKnownOne &= LHSKnownOne;
1070 RHSKnownZero &= LHSKnownZero;
1071 break;
1072 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001073 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001074 DemandedMask.zext(truncBf);
1075 RHSKnownZero.zext(truncBf);
1076 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001077 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001078 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001079 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001080 DemandedMask.trunc(BitWidth);
1081 RHSKnownZero.trunc(BitWidth);
1082 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001084 break;
1085 }
1086 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001087 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001089
1090 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1091 if (const VectorType *SrcVTy =
1092 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1093 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1094 // Don't touch a bitcast between vectors of different element counts.
1095 return false;
1096 } else
1097 // Don't touch a scalar-to-vector bitcast.
1098 return false;
1099 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1100 // Don't touch a vector-to-scalar bitcast.
1101 return false;
1102
Chris Lattner886ab6c2009-01-31 08:15:18 +00001103 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001104 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 return I;
1106 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 break;
1108 case Instruction::ZExt: {
1109 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001110 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001111
Zhou Shengd48653a2007-03-29 04:45:55 +00001112 DemandedMask.trunc(SrcBitWidth);
1113 RHSKnownZero.trunc(SrcBitWidth);
1114 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001116 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001117 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001118 DemandedMask.zext(BitWidth);
1119 RHSKnownZero.zext(BitWidth);
1120 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001121 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001122 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001123 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 break;
1125 }
1126 case Instruction::SExt: {
1127 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001128 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001129
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001132
Zhou Sheng01542f32007-03-29 02:26:30 +00001133 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001134 // If any of the sign extended bits are demanded, we know that the sign
1135 // bit is demanded.
1136 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001137 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001138
Zhou Shengd48653a2007-03-29 04:45:55 +00001139 InputDemandedBits.trunc(SrcBitWidth);
1140 RHSKnownZero.trunc(SrcBitWidth);
1141 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
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 InputDemandedBits.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
1150 // If the sign bit of the input is known set or clear, then we know the
1151 // top bits of the result.
1152
1153 // If the input sign bit is known zero, or if the NewBits are not demanded
1154 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001155 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001156 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001157 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1158 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001159 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001160 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 }
1162 break;
1163 }
1164 case Instruction::Add: {
1165 // Figure out what the input bits are. If the top bits of the and result
1166 // are not demanded, then the add doesn't demand them from its input
1167 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001168 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001169
1170 // If there is a constant on the RHS, there are a variety of xformations
1171 // we can do.
1172 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1173 // If null, this should be simplified elsewhere. Some of the xforms here
1174 // won't work if the RHS is zero.
1175 if (RHS->isZero())
1176 break;
1177
1178 // If the top bit of the output is demanded, demand everything from the
1179 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001180 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
1182 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001183 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001184 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
1187 // If the RHS of the add has bits set that can't affect the input, reduce
1188 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001189 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001191
1192 // Avoid excess work.
1193 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1194 break;
1195
1196 // Turn it into OR if input bits are zero.
1197 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1198 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001199 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001200 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001201 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 }
1203
1204 // We can say something about the output known-zero and known-one bits,
1205 // depending on potential carries from the input constant and the
1206 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1207 // bits set and the RHS constant is 0x01001, then we know we have a known
1208 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1209
1210 // To compute this, we first compute the potential carry bits. These are
1211 // the bits which may be modified. I'm not aware of a better way to do
1212 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001214 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001215
1216 // Now that we know which bits have carries, compute the known-1/0 sets.
1217
1218 // Bits are known one if they are known zero in one operand and one in the
1219 // other, and there is no input carry.
1220 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1221 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1222
1223 // Bits are known zero if they are known zero in both operands and there
1224 // is no input carry.
1225 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1226 } else {
1227 // If the high-bits of this ADD are not demanded, then it does not demand
1228 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001229 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 // Right fill the mask of bits for this ADD to demand the most
1231 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001232 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1234 LHSKnownZero, LHSKnownOne, Depth+1) ||
1235 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001237 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 }
1239 }
1240 break;
1241 }
1242 case Instruction::Sub:
1243 // If the high-bits of this SUB are not demanded, then it does not demand
1244 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001245 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 // Right fill the mask of bits for this SUB to demand the most
1247 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001248 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001249 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001250 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1251 LHSKnownZero, LHSKnownOne, Depth+1) ||
1252 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001256 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1257 // the known zeros and ones.
1258 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 break;
1260 case Instruction::Shl:
1261 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001262 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001263 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001264 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return I;
1267 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 RHSKnownZero <<= ShiftAmt;
1269 RHSKnownOne <<= ShiftAmt;
1270 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001271 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001272 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 }
1274 break;
1275 case Instruction::LShr:
1276 // For a logical shift right
1277 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001278 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001279
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001281 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001282 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001283 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 return I;
1285 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1287 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001288 if (ShiftAmt) {
1289 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001290 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001291 RHSKnownZero |= HighBits; // high bits known zero.
1292 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 }
1294 break;
1295 case Instruction::AShr:
1296 // If this is an arithmetic shift right and only the low-bit is set, we can
1297 // always convert this into a logical shr, even if the shift amount is
1298 // variable. The low bit of the shift cannot be an input sign bit unless
1299 // the shift amount is >= the size of the datatype, which is undefined.
1300 if (DemandedMask == 1) {
1301 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001302 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001303 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001305 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001306
1307 // If the sign bit is the only bit demanded by this ashr, then there is no
1308 // need to do it, the shift doesn't change the high bit.
1309 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001310 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001311
1312 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001313 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001314
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001317 // If any of the "high bits" are demanded, we should set the sign bit as
1318 // demanded.
1319 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1320 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 return I;
1324 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001326 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1328 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1329
1330 // Handle the sign bits.
1331 APInt SignBit(APInt::getSignBit(BitWidth));
1332 // Adjust to where it is now in the mask.
1333 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1334
1335 // If the input sign bit is known to be zero, or if none of the top bits
1336 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001337 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001338 (HighBits & ~DemandedMask) == HighBits) {
1339 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001340 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001341 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1344 RHSKnownOne |= HighBits;
1345 }
1346 }
1347 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001348 case Instruction::SRem:
1349 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001350 APInt RA = Rem->getValue().abs();
1351 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001352 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001354
Nick Lewycky8e394322008-11-02 02:41:50 +00001355 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001356 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001357 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001358 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001360
1361 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1362 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001363
1364 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365
Chris Lattner886ab6c2009-01-31 08:15:18 +00001366 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001367 }
1368 }
1369 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001370 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001371 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1372 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001373 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1374 KnownZero2, KnownOne2, Depth+1) ||
1375 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001376 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001377 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001378
Chris Lattner455e9ab2009-01-21 18:09:24 +00001379 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001380 Leaders = std::max(Leaders,
1381 KnownZero2.countLeadingOnes());
1382 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001383 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001385 case Instruction::Call:
1386 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1387 switch (II->getIntrinsicID()) {
1388 default: break;
1389 case Intrinsic::bswap: {
1390 // If the only bits demanded come from one byte of the bswap result,
1391 // just shift the input byte into position to eliminate the bswap.
1392 unsigned NLZ = DemandedMask.countLeadingZeros();
1393 unsigned NTZ = DemandedMask.countTrailingZeros();
1394
1395 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1396 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1397 // have 14 leading zeros, round to 8.
1398 NLZ &= ~7;
1399 NTZ &= ~7;
1400 // If we need exactly one byte, we can do this transformation.
1401 if (BitWidth-NLZ-NTZ == 8) {
1402 unsigned ResultBit = NTZ;
1403 unsigned InputBit = BitWidth-NTZ-8;
1404
1405 // Replace this with either a left or right shift to get the byte into
1406 // the right place.
1407 Instruction *NewVal;
1408 if (InputBit > ResultBit)
1409 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001410 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001411 else
1412 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001413 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001414 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001415 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001416 }
1417
1418 // TODO: Could compute known zero/one bits based on the input.
1419 break;
1420 }
1421 }
1422 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001423 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001424 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001425 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001426
1427 // If the client is only demanding bits that we know, return the known
1428 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001429 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1430 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001431 return false;
1432}
1433
Chris Lattner867b99f2006-10-05 06:55:50 +00001434
Mon P Wangaeb06d22008-11-10 04:46:22 +00001435/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001436/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001437/// actually used by the caller. This method analyzes which elements of the
1438/// operand are undef and returns that information in UndefElts.
1439///
1440/// If the information about demanded elements can be used to simplify the
1441/// operation, the operation is simplified, then the resultant value is
1442/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001443Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1444 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001445 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001446 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001447 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001448 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001449
1450 if (isa<UndefValue>(V)) {
1451 // If the entire vector is undefined, just return this info.
1452 UndefElts = EltMask;
1453 return 0;
1454 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1455 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001456 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001458
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001460 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1461 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001462 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001463
1464 std::vector<Constant*> Elts;
1465 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001466 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001468 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001469 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1470 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001471 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 } else { // Otherwise, defined.
1473 Elts.push_back(CP->getOperand(i));
1474 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001475
Chris Lattner867b99f2006-10-05 06:55:50 +00001476 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001477 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001478 return NewCP != CP ? NewCP : 0;
1479 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001480 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001482
1483 // Check if this is identity. If so, return 0 since we are not simplifying
1484 // anything.
1485 if (DemandedElts == ((1ULL << VWidth) -1))
1486 return 0;
1487
Reid Spencer9d6565a2007-02-15 02:26:10 +00001488 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001489 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001490 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001492 for (unsigned i = 0; i != VWidth; ++i) {
1493 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1494 Elts.push_back(Elt);
1495 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001496 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001497 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001498 }
1499
Dan Gohman488fbfc2008-09-09 18:11:14 +00001500 // Limit search depth.
1501 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001502 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001503
1504 // If multiple users are using the root value, procede with
1505 // simplification conservatively assuming that all elements
1506 // are needed.
1507 if (!V->hasOneUse()) {
1508 // Quit if we find multiple users of a non-root value though.
1509 // They'll be handled when it's their turn to be visited by
1510 // the main instcombine process.
1511 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001513 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001514
1515 // Conservatively assume that all elements are needed.
1516 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001517 }
1518
1519 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001520 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001521
1522 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001523 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 Value *TmpV;
1525 switch (I->getOpcode()) {
1526 default: break;
1527
1528 case Instruction::InsertElement: {
1529 // If this is a variable index, we don't know which element it overwrites.
1530 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001531 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001532 if (Idx == 0) {
1533 // Note that we can't propagate undef elt info, because we don't know
1534 // which elt is getting updated.
1535 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1536 UndefElts2, Depth+1);
1537 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1538 break;
1539 }
1540
1541 // If this is inserting an element that isn't demanded, remove this
1542 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001543 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001544 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1545 Worklist.Add(I);
1546 return I->getOperand(0);
1547 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001548
1549 // Otherwise, the element inserted overwrites whatever was there, so the
1550 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001551 APInt DemandedElts2 = DemandedElts;
1552 DemandedElts2.clear(IdxNo);
1553 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001554 UndefElts, Depth+1);
1555 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1556
1557 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001558 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001559 break;
1560 }
1561 case Instruction::ShuffleVector: {
1562 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001563 uint64_t LHSVWidth =
1564 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001565 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001566 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001567 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568 unsigned MaskVal = Shuffle->getMaskValue(i);
1569 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001570 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001572 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001573 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574 else
Evan Cheng388df622009-02-03 10:05:09 +00001575 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 }
1577 }
1578 }
1579
Nate Begeman7b254672009-02-11 22:36:25 +00001580 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001582 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001583 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1584
Nate Begeman7b254672009-02-11 22:36:25 +00001585 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1587 UndefElts3, Depth+1);
1588 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1589
1590 bool NewUndefElts = false;
1591 for (unsigned i = 0; i < VWidth; i++) {
1592 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001593 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001594 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001595 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001596 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001597 NewUndefElts = true;
1598 UndefElts.set(i);
1599 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001601 if (UndefElts3[MaskVal - LHSVWidth]) {
1602 NewUndefElts = true;
1603 UndefElts.set(i);
1604 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001605 }
1606 }
1607
1608 if (NewUndefElts) {
1609 // Add additional discovered undefs.
1610 std::vector<Constant*> Elts;
1611 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001612 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001613 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001614 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001615 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001616 Shuffle->getMaskValue(i)));
1617 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001618 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001619 MadeChange = true;
1620 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001621 break;
1622 }
Chris Lattner69878332007-04-14 22:29:23 +00001623 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001624 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001625 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1626 if (!VTy) break;
1627 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001628 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001629 unsigned Ratio;
1630
1631 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001632 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001633 // elements as are demanded of us.
1634 Ratio = 1;
1635 InputDemandedElts = DemandedElts;
1636 } else if (VWidth > InVWidth) {
1637 // Untested so far.
1638 break;
1639
1640 // If there are more elements in the result than there are in the source,
1641 // then an input element is live if any of the corresponding output
1642 // elements are live.
1643 Ratio = VWidth/InVWidth;
1644 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001645 if (DemandedElts[OutIdx])
1646 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001647 }
1648 } else {
1649 // Untested so far.
1650 break;
1651
1652 // If there are more elements in the source than there are in the result,
1653 // then an input element is live if the corresponding output element is
1654 // live.
1655 Ratio = InVWidth/VWidth;
1656 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001657 if (DemandedElts[InIdx/Ratio])
1658 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001659 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001660
Chris Lattner69878332007-04-14 22:29:23 +00001661 // div/rem demand all inputs, because they don't want divide by zero.
1662 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1663 UndefElts2, Depth+1);
1664 if (TmpV) {
1665 I->setOperand(0, TmpV);
1666 MadeChange = true;
1667 }
1668
1669 UndefElts = UndefElts2;
1670 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001671 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001672 // If there are more elements in the result than there are in the source,
1673 // then an output element is undef if the corresponding input element is
1674 // undef.
1675 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001676 if (UndefElts2[OutIdx/Ratio])
1677 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001678 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001679 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001680 // If there are more elements in the source than there are in the result,
1681 // then a result element is undef if all of the corresponding input
1682 // elements are undef.
1683 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1684 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001685 if (!UndefElts2[InIdx]) // Not undef?
1686 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001687 }
1688 break;
1689 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001690 case Instruction::And:
1691 case Instruction::Or:
1692 case Instruction::Xor:
1693 case Instruction::Add:
1694 case Instruction::Sub:
1695 case Instruction::Mul:
1696 // div/rem demand all inputs, because they don't want divide by zero.
1697 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1698 UndefElts, Depth+1);
1699 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1700 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1701 UndefElts2, Depth+1);
1702 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1703
1704 // Output elements are undefined if both are undefined. Consider things
1705 // like undef&0. The result is known zero, not undef.
1706 UndefElts &= UndefElts2;
1707 break;
1708
1709 case Instruction::Call: {
1710 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1711 if (!II) break;
1712 switch (II->getIntrinsicID()) {
1713 default: break;
1714
1715 // Binary vector operations that work column-wise. A dest element is a
1716 // function of the corresponding input elements from the two inputs.
1717 case Intrinsic::x86_sse_sub_ss:
1718 case Intrinsic::x86_sse_mul_ss:
1719 case Intrinsic::x86_sse_min_ss:
1720 case Intrinsic::x86_sse_max_ss:
1721 case Intrinsic::x86_sse2_sub_sd:
1722 case Intrinsic::x86_sse2_mul_sd:
1723 case Intrinsic::x86_sse2_min_sd:
1724 case Intrinsic::x86_sse2_max_sd:
1725 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1726 UndefElts, Depth+1);
1727 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1728 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1729 UndefElts2, Depth+1);
1730 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1731
1732 // If only the low elt is demanded and this is a scalarizable intrinsic,
1733 // scalarize it now.
1734 if (DemandedElts == 1) {
1735 switch (II->getIntrinsicID()) {
1736 default: break;
1737 case Intrinsic::x86_sse_sub_ss:
1738 case Intrinsic::x86_sse_mul_ss:
1739 case Intrinsic::x86_sse2_sub_sd:
1740 case Intrinsic::x86_sse2_mul_sd:
1741 // TODO: Lower MIN/MAX/ABS/etc
1742 Value *LHS = II->getOperand(1);
1743 Value *RHS = II->getOperand(2);
1744 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001745 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001746 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001747 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001748 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001749
1750 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001751 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001752 case Intrinsic::x86_sse_sub_ss:
1753 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001754 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001755 II->getName()), *II);
1756 break;
1757 case Intrinsic::x86_sse_mul_ss:
1758 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001759 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001760 II->getName()), *II);
1761 break;
1762 }
1763
1764 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001765 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001766 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001767 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001768 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001769 return New;
1770 }
1771 }
1772
1773 // Output elements are undefined if both are undefined. Consider things
1774 // like undef&0. The result is known zero, not undef.
1775 UndefElts &= UndefElts2;
1776 break;
1777 }
1778 break;
1779 }
1780 }
1781 return MadeChange ? I : 0;
1782}
1783
Dan Gohman45b4e482008-05-19 22:14:15 +00001784
Chris Lattner564a7272003-08-13 19:01:45 +00001785/// AssociativeOpt - Perform an optimization on an associative operator. This
1786/// function is designed to check a chain of associative operators for a
1787/// potential to apply a certain optimization. Since the optimization may be
1788/// applicable if the expression was reassociated, this checks the chain, then
1789/// reassociates the expression as necessary to expose the optimization
1790/// opportunity. This makes use of a special Functor, which must define
1791/// 'shouldApply' and 'apply' methods.
1792///
1793template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001794static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001795 unsigned Opcode = Root.getOpcode();
1796 Value *LHS = Root.getOperand(0);
1797
1798 // Quick check, see if the immediate LHS matches...
1799 if (F.shouldApply(LHS))
1800 return F.apply(Root);
1801
1802 // Otherwise, if the LHS is not of the same opcode as the root, return.
1803 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001804 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001805 // Should we apply this transform to the RHS?
1806 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1807
1808 // If not to the RHS, check to see if we should apply to the LHS...
1809 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1810 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1811 ShouldApply = true;
1812 }
1813
1814 // If the functor wants to apply the optimization to the RHS of LHSI,
1815 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1816 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001817 // Now all of the instructions are in the current basic block, go ahead
1818 // and perform the reassociation.
1819 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1820
1821 // First move the selected RHS to the LHS of the root...
1822 Root.setOperand(0, LHSI->getOperand(1));
1823
1824 // Make what used to be the LHS of the root be the user of the root...
1825 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001826 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001827 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001828 return 0;
1829 }
Chris Lattner65725312004-04-16 18:08:07 +00001830 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001831 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001832 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001833 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001834 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001835
1836 // Now propagate the ExtraOperand down the chain of instructions until we
1837 // get to LHSI.
1838 while (TmpLHSI != LHSI) {
1839 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001840 // Move the instruction to immediately before the chain we are
1841 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001842 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001843 ARI = NextLHSI;
1844
Chris Lattner564a7272003-08-13 19:01:45 +00001845 Value *NextOp = NextLHSI->getOperand(1);
1846 NextLHSI->setOperand(1, ExtraOperand);
1847 TmpLHSI = NextLHSI;
1848 ExtraOperand = NextOp;
1849 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001850
Chris Lattner564a7272003-08-13 19:01:45 +00001851 // Now that the instructions are reassociated, have the functor perform
1852 // the transformation...
1853 return F.apply(Root);
1854 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001855
Chris Lattner564a7272003-08-13 19:01:45 +00001856 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1857 }
1858 return 0;
1859}
1860
Dan Gohman844731a2008-05-13 00:00:25 +00001861namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001862
Nick Lewycky02d639f2008-05-23 04:34:58 +00001863// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001864struct AddRHS {
1865 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001866 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001867 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1868 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001869 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001870 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001871 }
1872};
1873
1874// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1875// iff C1&C2 == 0
1876struct AddMaskingAnd {
1877 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001878 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001879 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001880 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001881 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001882 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001883 }
1884 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001885 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001886 }
1887};
1888
Dan Gohman844731a2008-05-13 00:00:25 +00001889}
1890
Chris Lattner6e7ba452005-01-01 16:22:27 +00001891static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001892 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001893 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001894 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001895
Chris Lattner2eefe512004-04-09 19:05:30 +00001896 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001897 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1898 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001899
Chris Lattner2eefe512004-04-09 19:05:30 +00001900 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1901 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001902 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1903 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001904 }
1905
1906 Value *Op0 = SO, *Op1 = ConstOperand;
1907 if (!ConstIsRHS)
1908 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001909
Chris Lattner6e7ba452005-01-01 16:22:27 +00001910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001911 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1912 SO->getName()+".op");
1913 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1914 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1915 SO->getName()+".cmp");
1916 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1917 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1918 SO->getName()+".cmp");
1919 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001920}
1921
1922// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1923// constant as the other operand, try to fold the binary operator into the
1924// select arguments. This also works for Cast instructions, which obviously do
1925// not have a second operand.
1926static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1927 InstCombiner *IC) {
1928 // Don't modify shared select instructions
1929 if (!SI->hasOneUse()) return 0;
1930 Value *TV = SI->getOperand(1);
1931 Value *FV = SI->getOperand(2);
1932
1933 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001934 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001935 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001936
Chris Lattner6e7ba452005-01-01 16:22:27 +00001937 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1938 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1939
Gabor Greif051a9502008-04-06 20:25:17 +00001940 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1941 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001942 }
1943 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001944}
1945
Chris Lattner4e998b22004-09-29 05:07:12 +00001946
Chris Lattner5d1704d2009-09-27 19:57:57 +00001947/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1948/// has a PHI node as operand #0, see if we can fold the instruction into the
1949/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00001950///
1951/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1952/// that would normally be unprofitable because they strongly encourage jump
1953/// threading.
1954Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1955 bool AllowAggressive) {
1956 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00001957 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001958 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00001959 if (NumPHIValues == 0 ||
1960 // We normally only transform phis with a single use, unless we're trying
1961 // hard to make jump threading happen.
1962 (!PN->hasOneUse() && !AllowAggressive))
1963 return 0;
1964
1965
Chris Lattner5d1704d2009-09-27 19:57:57 +00001966 // Check to see if all of the operands of the PHI are simple constants
1967 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001968 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1969 // bail out. We don't do arbitrary constant expressions here because moving
1970 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001971 BasicBlock *NonConstBB = 0;
1972 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00001973 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1974 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001975 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001976 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 NonConstBB = PN->getIncomingBlock(i);
1978
1979 // If the incoming non-constant value is in I's block, we have an infinite
1980 // loop.
1981 if (NonConstBB == I.getParent())
1982 return 0;
1983 }
1984
1985 // If there is exactly one non-constant value, we can insert a copy of the
1986 // operation in that block. However, if this is a critical edge, we would be
1987 // inserting the computation one some other paths (e.g. inside a loop). Only
1988 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00001989 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001990 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1991 if (!BI || !BI->isUnconditional()) return 0;
1992 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001993
1994 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001995 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001996 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001997 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001998 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001999
2000 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002001 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2002 // We only currently try to fold the condition of a select when it is a phi,
2003 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002004 Value *TrueV = SI->getTrueValue();
2005 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002006 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002007 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002008 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002009 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2010 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002011 Value *InV = 0;
2012 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002013 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002014 } else {
2015 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002016 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2017 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002018 "phitmp", NonConstBB->getTerminator());
2019 Worklist.Add(cast<Instruction>(InV));
2020 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002021 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002022 }
2023 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002024 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002025 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002026 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002027 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002028 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002029 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002030 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002031 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002032 } else {
2033 assert(PN->getIncomingBlock(i) == NonConstBB);
2034 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002035 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002036 PN->getIncomingValue(i), C, "phitmp",
2037 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002038 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002039 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002040 CI->getPredicate(),
2041 PN->getIncomingValue(i), C, "phitmp",
2042 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002043 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002044 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002045
Chris Lattner7a1e9242009-08-30 06:13:40 +00002046 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002047 }
2048 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002049 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002050 } else {
2051 CastInst *CI = cast<CastInst>(&I);
2052 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002053 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002054 Value *InV;
2055 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002056 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002057 } else {
2058 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002059 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002060 I.getType(), "phitmp",
2061 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002062 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002063 }
2064 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002065 }
2066 }
2067 return ReplaceInstUsesWith(I, NewPN);
2068}
2069
Chris Lattner2454a2e2008-01-29 06:52:45 +00002070
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002071/// WillNotOverflowSignedAdd - Return true if we can prove that:
2072/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2073/// This basically requires proving that the add in the original type would not
2074/// overflow to change the sign bit or have a carry out.
2075bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2076 // There are different heuristics we can use for this. Here are some simple
2077 // ones.
2078
2079 // Add has the property that adding any two 2's complement numbers can only
2080 // have one carry bit which can change a sign. As such, if LHS and RHS each
2081 // have at least two sign bits, we know that the addition of the two values will
2082 // sign extend fine.
2083 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2084 return true;
2085
2086
2087 // If one of the operands only has one non-zero bit, and if the other operand
2088 // has a known-zero bit in a more significant place than it (not including the
2089 // sign bit) the ripple may go up to and fill the zero, but won't change the
2090 // sign. For example, (X & ~4) + 1.
2091
2092 // TODO: Implement.
2093
2094 return false;
2095}
2096
Chris Lattner2454a2e2008-01-29 06:52:45 +00002097
Chris Lattner7e708292002-06-25 16:13:24 +00002098Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002099 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002100 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002101
Chris Lattner66331a42004-04-10 22:01:55 +00002102 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002103 // X + undef -> undef
2104 if (isa<UndefValue>(RHS))
2105 return ReplaceInstUsesWith(I, RHS);
2106
Chris Lattner66331a42004-04-10 22:01:55 +00002107 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002108 if (RHSC->isNullValue())
2109 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002110
Chris Lattner66331a42004-04-10 22:01:55 +00002111 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002112 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002113 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002114 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002115 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002116 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002117
2118 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2119 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002120 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002121 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002122
Eli Friedman709b33d2009-07-13 22:27:52 +00002123 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002124 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002125 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002126 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002127 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002128
2129 if (isa<PHINode>(LHS))
2130 if (Instruction *NV = FoldOpIntoPhi(I))
2131 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002132
Chris Lattner4f637d42006-01-06 17:59:59 +00002133 ConstantInt *XorRHS = 0;
2134 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002135 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002136 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002137 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002138 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002139
Zhou Sheng4351c642007-04-02 08:20:41 +00002140 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002141 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2142 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002143 do {
2144 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002145 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2146 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002147 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2148 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002149 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002150 if (!MaskedValueIsZero(XorLHS,
2151 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002152 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002153 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002154 }
2155 }
2156 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002157 C0080Val = APIntOps::lshr(C0080Val, Size);
2158 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2159 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002160
Reid Spencer35c38852007-03-28 01:36:16 +00002161 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002162 // with funny bit widths then this switch statement should be removed. It
2163 // is just here to get the size of the "middle" type back up to something
2164 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002165 const Type *MiddleType = 0;
2166 switch (Size) {
2167 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002168 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2169 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2170 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002171 }
2172 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002173 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002174 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002175 }
2176 }
Chris Lattner66331a42004-04-10 22:01:55 +00002177 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002178
Owen Anderson1d0be152009-08-13 21:58:54 +00002179 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002180 return BinaryOperator::CreateXor(LHS, RHS);
2181
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002182 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002183 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002184 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002185 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002186
2187 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2188 if (RHSI->getOpcode() == Instruction::Sub)
2189 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2190 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2191 }
2192 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2193 if (LHSI->getOpcode() == Instruction::Sub)
2194 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2195 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2196 }
Robert Bocchino71698282004-07-27 21:02:21 +00002197 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002198
Chris Lattner5c4afb92002-05-08 22:46:53 +00002199 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002200 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002201 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002202 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002203 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002204 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002205 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002206 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002207 }
2208
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002209 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002210 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002211
2212 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002213 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002214 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002215 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002216
Misha Brukmanfd939082005-04-21 23:48:37 +00002217
Chris Lattner50af16a2004-11-13 19:50:12 +00002218 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002219 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002220 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002221 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002222
2223 // X*C1 + X*C2 --> X * (C1+C2)
2224 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002225 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002226 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002227 }
2228
2229 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002230 if (dyn_castFoldableMul(RHS, C2) == LHS)
2231 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002232
Chris Lattnere617c9e2007-01-05 02:17:46 +00002233 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002234 if (dyn_castNotVal(LHS) == RHS ||
2235 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002236 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002237
Chris Lattnerad3448c2003-02-18 19:57:07 +00002238
Chris Lattner564a7272003-08-13 19:01:45 +00002239 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002240 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2241 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002242 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002243
2244 // A+B --> A|B iff A and B have no bits set in common.
2245 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2246 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2247 APInt LHSKnownOne(IT->getBitWidth(), 0);
2248 APInt LHSKnownZero(IT->getBitWidth(), 0);
2249 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2250 if (LHSKnownZero != 0) {
2251 APInt RHSKnownOne(IT->getBitWidth(), 0);
2252 APInt RHSKnownZero(IT->getBitWidth(), 0);
2253 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2254
2255 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002256 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002257 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002258 }
2259 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002260
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002261 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002262 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002263 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002264 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2265 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002266 if (W != Y) {
2267 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002268 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002269 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002270 std::swap(W, X);
2271 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002272 std::swap(Y, Z);
2273 std::swap(W, X);
2274 }
2275 }
2276
2277 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002278 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002279 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002280 }
2281 }
2282 }
2283
Chris Lattner6b032052003-10-02 15:11:26 +00002284 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002285 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002286 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002287 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002288
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002289 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002290 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002291 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002292 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002293 if (Anded == CRHS) {
2294 // See if all bits from the first bit set in the Add RHS up are included
2295 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002296 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002297
2298 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002299 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002300
2301 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002302 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002303
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002304 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2305 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002306 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002307 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002308 }
2309 }
2310 }
2311
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002312 // Try to fold constant add into select arguments.
2313 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002314 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002315 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002316 }
2317
Chris Lattner42790482007-12-20 01:56:58 +00002318 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002319 {
2320 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002321 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002322 if (!SI) {
2323 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002324 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002325 }
Chris Lattner42790482007-12-20 01:56:58 +00002326 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002327 Value *TV = SI->getTrueValue();
2328 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002329 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002330
2331 // Can we fold the add into the argument of the select?
2332 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002333 if (match(FV, m_Zero()) &&
2334 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002335 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002336 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002337 if (match(TV, m_Zero()) &&
2338 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002339 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002340 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002341 }
2342 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002343
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002344 // Check for (add (sext x), y), see if we can merge this into an
2345 // integer add followed by a sext.
2346 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2347 // (add (sext x), cst) --> (sext (add x, cst'))
2348 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2349 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002350 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002351 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002352 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002353 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2354 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002355 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2356 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002357 return new SExtInst(NewAdd, I.getType());
2358 }
2359 }
2360
2361 // (add (sext x), (sext y)) --> (sext (add int x, y))
2362 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2363 // Only do this if x/y have the same type, if at last one of them has a
2364 // single use (so we don't increase the number of sexts), and if the
2365 // integer add will not overflow.
2366 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2367 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2368 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2369 RHSConv->getOperand(0))) {
2370 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002371 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2372 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002373 return new SExtInst(NewAdd, I.getType());
2374 }
2375 }
2376 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002377
2378 return Changed ? &I : 0;
2379}
2380
2381Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2382 bool Changed = SimplifyCommutative(I);
2383 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2384
2385 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2386 // X + 0 --> X
2387 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002388 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002389 (I.getType())->getValueAPF()))
2390 return ReplaceInstUsesWith(I, LHS);
2391 }
2392
2393 if (isa<PHINode>(LHS))
2394 if (Instruction *NV = FoldOpIntoPhi(I))
2395 return NV;
2396 }
2397
2398 // -A + B --> B - A
2399 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002400 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002401 return BinaryOperator::CreateFSub(RHS, LHSV);
2402
2403 // A + -B --> A - B
2404 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002405 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002406 return BinaryOperator::CreateFSub(LHS, V);
2407
2408 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2409 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2410 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2411 return ReplaceInstUsesWith(I, LHS);
2412
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002413 // Check for (add double (sitofp x), y), see if we can merge this into an
2414 // integer add followed by a promotion.
2415 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2416 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2417 // ... if the constant fits in the integer value. This is useful for things
2418 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2419 // requires a constant pool load, and generally allows the add to be better
2420 // instcombined.
2421 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2422 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002423 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002424 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002425 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002426 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2427 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002428 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2429 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002430 return new SIToFPInst(NewAdd, I.getType());
2431 }
2432 }
2433
2434 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2435 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2436 // Only do this if x/y have the same type, if at last one of them has a
2437 // single use (so we don't increase the number of int->fp conversions),
2438 // and if the integer add will not overflow.
2439 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2440 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2441 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2442 RHSConv->getOperand(0))) {
2443 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002444 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2445 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002446 return new SIToFPInst(NewAdd, I.getType());
2447 }
2448 }
2449 }
2450
Chris Lattner7e708292002-06-25 16:13:24 +00002451 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002452}
2453
Chris Lattner7e708292002-06-25 16:13:24 +00002454Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002456
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002457 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002459
Chris Lattner233f7dc2002-08-12 21:17:25 +00002460 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002461 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002462 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002463
Chris Lattnere87597f2004-10-16 18:11:37 +00002464 if (isa<UndefValue>(Op0))
2465 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2466 if (isa<UndefValue>(Op1))
2467 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2468
Chris Lattnerd65460f2003-11-05 01:06:05 +00002469 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2470 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002471 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002472 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002473
Chris Lattnerd65460f2003-11-05 01:06:05 +00002474 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002475 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002476 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002477 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002478
Chris Lattner76b7a062007-01-15 07:02:54 +00002479 // -(X >>u 31) -> (X >>s 31)
2480 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002481 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002482 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002483 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002484 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002485 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002486 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002487 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002488 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002489 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002490 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002491 }
2492 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002493 }
2494 else if (SI->getOpcode() == Instruction::AShr) {
2495 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2496 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002497 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002498 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002499 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002500 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002501 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002502 }
2503 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002504 }
2505 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002506 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002507
2508 // Try to fold constant sub into select arguments.
2509 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002510 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002511 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002512
2513 // C - zext(bool) -> bool ? C - 1 : C
2514 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002515 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002516 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002517 }
2518
Owen Anderson1d0be152009-08-13 21:58:54 +00002519 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002520 return BinaryOperator::CreateXor(Op0, Op1);
2521
Chris Lattner43d84d62005-04-07 16:15:25 +00002522 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002523 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002524 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002525 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002526 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002527 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002528 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002529 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002530 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2531 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2532 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002533 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002534 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002535 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002536 }
2537
Chris Lattnerfd059242003-10-15 16:48:29 +00002538 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002539 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2540 // is not used by anyone else...
2541 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002542 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002543 // Swap the two operands of the subexpr...
2544 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2545 Op1I->setOperand(0, IIOp1);
2546 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002547
Chris Lattnera2881962003-02-18 19:28:33 +00002548 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002549 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002550 }
2551
2552 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2553 //
2554 if (Op1I->getOpcode() == Instruction::And &&
2555 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2556 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2557
Chris Lattner74381062009-08-30 07:44:24 +00002558 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002559 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002560 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002561
Reid Spencerac5209e2006-10-16 23:08:08 +00002562 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002563 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002564 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002565 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002566 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002567 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002568 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002569
Chris Lattnerad3448c2003-02-18 19:57:07 +00002570 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002571 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002572 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002573 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002574 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002575 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002576 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002577 }
Chris Lattner40371712002-05-09 01:29:19 +00002578 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002579 }
Chris Lattnera2881962003-02-18 19:28:33 +00002580
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002581 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2582 if (Op0I->getOpcode() == Instruction::Add) {
2583 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2584 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2585 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2586 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2587 } else if (Op0I->getOpcode() == Instruction::Sub) {
2588 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002589 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002590 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002591 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002593
Chris Lattner50af16a2004-11-13 19:50:12 +00002594 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002595 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002596 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002597 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002598
Chris Lattner50af16a2004-11-13 19:50:12 +00002599 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002600 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002601 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002602 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002603 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002604}
2605
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002606Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2608
2609 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002610 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002611 return BinaryOperator::CreateFAdd(Op0, V);
2612
2613 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2614 if (Op1I->getOpcode() == Instruction::FAdd) {
2615 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002616 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002617 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002618 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002619 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002620 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002621 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002622 }
2623
2624 return 0;
2625}
2626
Chris Lattnera0141b92007-07-15 20:42:37 +00002627/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2628/// comparison only checks the sign bit. If it only checks the sign bit, set
2629/// TrueIfSigned if the result of the comparison is true when the input value is
2630/// signed.
2631static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2632 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002633 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002634 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2635 TrueIfSigned = true;
2636 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002637 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2638 TrueIfSigned = true;
2639 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002640 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2641 TrueIfSigned = false;
2642 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002643 case ICmpInst::ICMP_UGT:
2644 // True if LHS u> RHS and RHS == high-bit-mask - 1
2645 TrueIfSigned = true;
2646 return RHS->getValue() ==
2647 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2648 case ICmpInst::ICMP_UGE:
2649 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2650 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002651 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002652 default:
2653 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002654 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002655}
2656
Chris Lattner7e708292002-06-25 16:13:24 +00002657Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002658 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002660
Chris Lattnera2498472009-10-11 21:36:10 +00002661 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002662 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002663
Chris Lattner8af304a2009-10-11 07:53:15 +00002664 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002665 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2666 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002667
2668 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002669 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002670 if (SI->getOpcode() == Instruction::Shl)
2671 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002673 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002674
Zhou Sheng843f07672007-04-19 05:39:12 +00002675 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002676 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002677 if (CI->equalsInt(1)) // X * 1 == X
2678 return ReplaceInstUsesWith(I, Op0);
2679 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002680 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002681
Zhou Sheng97b52c22007-03-29 01:57:21 +00002682 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002683 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002685 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002686 }
Chris Lattnera2498472009-10-11 21:36:10 +00002687 } else if (isa<VectorType>(Op1C->getType())) {
2688 if (Op1C->isNullValue())
2689 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002690
Chris Lattnera2498472009-10-11 21:36:10 +00002691 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002692 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002693 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002694
2695 // As above, vector X*splat(1.0) -> X in all defined cases.
2696 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002697 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2698 if (CI->equalsInt(1))
2699 return ReplaceInstUsesWith(I, Op0);
2700 }
2701 }
Chris Lattnera2881962003-02-18 19:28:33 +00002702 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002703
2704 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2705 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002706 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002707 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002708 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2709 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002710 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002711
2712 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002713
2714 // Try to fold constant mul into select arguments.
2715 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002716 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002717 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002718
2719 if (isa<PHINode>(Op0))
2720 if (Instruction *NV = FoldOpIntoPhi(I))
2721 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002722 }
2723
Dan Gohman186a6362009-08-12 16:04:34 +00002724 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002725 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002726 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002727
Nick Lewycky0c730792008-11-21 07:33:58 +00002728 // (X / Y) * Y = X - (X % Y)
2729 // (X / Y) * -Y = (X % Y) - X
2730 {
Chris Lattnera2498472009-10-11 21:36:10 +00002731 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00002732 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2733 if (!BO ||
2734 (BO->getOpcode() != Instruction::UDiv &&
2735 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00002736 Op1C = Op0;
2737 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002738 }
Chris Lattnera2498472009-10-11 21:36:10 +00002739 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00002740 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002741 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00002742 (BO->getOpcode() == Instruction::UDiv ||
2743 BO->getOpcode() == Instruction::SDiv)) {
2744 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2745
Dan Gohmanfa94b942009-08-12 16:33:09 +00002746 // If the division is exact, X % Y is zero.
2747 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2748 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00002749 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00002750 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00002751 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00002752 }
2753
Chris Lattner74381062009-08-30 07:44:24 +00002754 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002755 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002756 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002757 else
Chris Lattner74381062009-08-30 07:44:24 +00002758 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002759 Rem->takeName(BO);
2760
Chris Lattnera2498472009-10-11 21:36:10 +00002761 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00002762 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002763 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002764 }
2765 }
2766
Chris Lattner8af304a2009-10-11 07:53:15 +00002767 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00002768 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00002769 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002770
Chris Lattner8af304a2009-10-11 07:53:15 +00002771 // X*(1 << Y) --> X << Y
2772 // (1 << Y)*X --> X << Y
2773 {
2774 Value *Y;
2775 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00002776 return BinaryOperator::CreateShl(Op1, Y);
2777 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00002778 return BinaryOperator::CreateShl(Op0, Y);
2779 }
2780
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 // If one of the operands of the multiply is a cast from a boolean value, then
2782 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00002783 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2784 if (!isa<VectorType>(I.getType())) {
2785 // -2 is "-1 << 1" so it is all bits set except the low one.
2786 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), -2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00002787
Chris Lattnerd2c58362009-10-11 21:29:45 +00002788 Value *BoolCast = 0, *OtherOp = 0;
2789 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00002790 BoolCast = Op0, OtherOp = Op1;
2791 else if (MaskedValueIsZero(Op1, Negative2))
2792 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00002793
Chris Lattner0036e3a2009-10-11 21:22:21 +00002794 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00002795 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2796 BoolCast, "tmp");
2797 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002798 }
2799 }
2800
Chris Lattner7e708292002-06-25 16:13:24 +00002801 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002802}
2803
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002804Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2805 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002806 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002807
2808 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00002809 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2810 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002811 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2812 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2813 if (Op1F->isExactlyValue(1.0))
2814 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00002815 } else if (isa<VectorType>(Op1C->getType())) {
2816 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002817 // As above, vector X*splat(1.0) -> X in all defined cases.
2818 if (Constant *Splat = Op1V->getSplatValue()) {
2819 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2820 if (F->isExactlyValue(1.0))
2821 return ReplaceInstUsesWith(I, Op0);
2822 }
2823 }
2824 }
2825
2826 // Try to fold constant mul into select arguments.
2827 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2828 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2829 return R;
2830
2831 if (isa<PHINode>(Op0))
2832 if (Instruction *NV = FoldOpIntoPhi(I))
2833 return NV;
2834 }
2835
Dan Gohman186a6362009-08-12 16:04:34 +00002836 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002837 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002838 return BinaryOperator::CreateFMul(Op0v, Op1v);
2839
2840 return Changed ? &I : 0;
2841}
2842
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002843/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2844/// instruction.
2845bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2846 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2847
2848 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2849 int NonNullOperand = -1;
2850 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2851 if (ST->isNullValue())
2852 NonNullOperand = 2;
2853 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2854 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2855 if (ST->isNullValue())
2856 NonNullOperand = 1;
2857
2858 if (NonNullOperand == -1)
2859 return false;
2860
2861 Value *SelectCond = SI->getOperand(0);
2862
2863 // Change the div/rem to use 'Y' instead of the select.
2864 I.setOperand(1, SI->getOperand(NonNullOperand));
2865
2866 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2867 // problem. However, the select, or the condition of the select may have
2868 // multiple uses. Based on our knowledge that the operand must be non-zero,
2869 // propagate the known value for the select into other uses of it, and
2870 // propagate a known value of the condition into its other users.
2871
2872 // If the select and condition only have a single use, don't bother with this,
2873 // early exit.
2874 if (SI->use_empty() && SelectCond->hasOneUse())
2875 return true;
2876
2877 // Scan the current block backward, looking for other uses of SI.
2878 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2879
2880 while (BBI != BBFront) {
2881 --BBI;
2882 // If we found a call to a function, we can't assume it will return, so
2883 // information from below it cannot be propagated above it.
2884 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2885 break;
2886
2887 // Replace uses of the select or its condition with the known values.
2888 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2889 I != E; ++I) {
2890 if (*I == SI) {
2891 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002892 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002893 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002894 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2895 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002896 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002897 }
2898 }
2899
2900 // If we past the instruction, quit looking for it.
2901 if (&*BBI == SI)
2902 SI = 0;
2903 if (&*BBI == SelectCond)
2904 SelectCond = 0;
2905
2906 // If we ran out of things to eliminate, break out of the loop.
2907 if (SelectCond == 0 && SI == 0)
2908 break;
2909
2910 }
2911 return true;
2912}
2913
2914
Reid Spencer1628cec2006-10-26 06:15:43 +00002915/// This function implements the transforms on div instructions that work
2916/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2917/// used by the visitors to those instructions.
2918/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002919Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002920 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002921
Chris Lattner50b2ca42008-02-19 06:12:18 +00002922 // undef / X -> 0 for integer.
2923 // undef / X -> undef for FP (the undef could be a snan).
2924 if (isa<UndefValue>(Op0)) {
2925 if (Op0->getType()->isFPOrFPVector())
2926 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002927 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002928 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002929
2930 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002931 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002932 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002933
Reid Spencer1628cec2006-10-26 06:15:43 +00002934 return 0;
2935}
Misha Brukmanfd939082005-04-21 23:48:37 +00002936
Reid Spencer1628cec2006-10-26 06:15:43 +00002937/// This function implements the transforms common to both integer division
2938/// instructions (udiv and sdiv). It is called by the visitors to those integer
2939/// division instructions.
2940/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002941Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002942 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2943
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002944 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002945 if (Op0 == Op1) {
2946 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002947 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002948 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002949 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002950 }
2951
Owen Andersoneed707b2009-07-24 23:12:02 +00002952 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002953 return ReplaceInstUsesWith(I, CI);
2954 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002955
Reid Spencer1628cec2006-10-26 06:15:43 +00002956 if (Instruction *Common = commonDivTransforms(I))
2957 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002958
2959 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2960 // This does not apply for fdiv.
2961 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2962 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002963
2964 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2965 // div X, 1 == X
2966 if (RHS->equalsInt(1))
2967 return ReplaceInstUsesWith(I, Op0);
2968
2969 // (X / C1) / C2 -> X / (C1*C2)
2970 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2971 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2972 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002973 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002974 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002976 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002977 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002978 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002979 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002980
Reid Spencerbca0e382007-03-23 20:05:17 +00002981 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002982 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2983 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2984 return R;
2985 if (isa<PHINode>(Op0))
2986 if (Instruction *NV = FoldOpIntoPhi(I))
2987 return NV;
2988 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002989 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002990
Chris Lattnera2881962003-02-18 19:28:33 +00002991 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002992 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002993 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002995
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002996 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002997 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002998 return ReplaceInstUsesWith(I, Op0);
2999
Nick Lewycky895f0852008-11-27 20:21:08 +00003000 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3001 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3002 // div X, 1 == X
3003 if (X->isOne())
3004 return ReplaceInstUsesWith(I, Op0);
3005 }
3006
Reid Spencer1628cec2006-10-26 06:15:43 +00003007 return 0;
3008}
3009
3010Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3012
3013 // Handle the integer div common cases
3014 if (Instruction *Common = commonIDivTransforms(I))
3015 return Common;
3016
Reid Spencer1628cec2006-10-26 06:15:43 +00003017 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003018 // X udiv C^2 -> X >> C
3019 // Check to see if this is an unsigned division with an exact power of 2,
3020 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003021 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003022 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003023 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003024
3025 // X udiv C, where C >= signbit
3026 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003027 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003028 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003029 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003030 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003031 }
3032
3033 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003034 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003035 if (RHSI->getOpcode() == Instruction::Shl &&
3036 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003037 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003038 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003039 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003040 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003041 if (uint32_t C2 = C1.logBase2())
3042 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003043 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003044 }
3045 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003046 }
3047
Reid Spencer1628cec2006-10-26 06:15:43 +00003048 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3049 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003050 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003051 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003052 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003053 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003054 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003055 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003056 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003057 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003058 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003059 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003060
3061 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003062 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003063 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003064
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003065 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003066 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003067 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003068 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003069 return 0;
3070}
3071
Reid Spencer1628cec2006-10-26 06:15:43 +00003072Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3073 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3074
3075 // Handle the integer div common cases
3076 if (Instruction *Common = commonIDivTransforms(I))
3077 return Common;
3078
3079 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3080 // sdiv X, -1 == -X
3081 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003082 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003083
Dan Gohmanfa94b942009-08-12 16:33:09 +00003084 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003085 if (cast<SDivOperator>(&I)->isExact() &&
3086 RHS->getValue().isNonNegative() &&
3087 RHS->getValue().isPowerOf2()) {
3088 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3089 RHS->getValue().exactLogBase2());
3090 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3091 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003092
3093 // -X/C --> X/-C provided the negation doesn't overflow.
3094 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3095 if (isa<Constant>(Sub->getOperand(0)) &&
3096 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003097 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003098 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3099 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003100 }
3101
3102 // If the sign bits of both operands are zero (i.e. we can prove they are
3103 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003104 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003105 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003106 if (MaskedValueIsZero(Op0, Mask)) {
3107 if (MaskedValueIsZero(Op1, Mask)) {
3108 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3109 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3110 }
3111 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003112 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003113 ShiftedInt->getValue().isPowerOf2()) {
3114 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3115 // Safe because the only negative value (1 << Y) can take on is
3116 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3117 // the sign bit set.
3118 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3119 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003120 }
Eli Friedman8be17392009-07-18 09:53:21 +00003121 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003122
3123 return 0;
3124}
3125
3126Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3127 return commonDivTransforms(I);
3128}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003129
Reid Spencer0a783f72006-11-02 01:53:59 +00003130/// This function implements the transforms on rem instructions that work
3131/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3132/// is used by the visitors to those instructions.
3133/// @brief Transforms common to all three rem instructions
3134Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003136
Chris Lattner50b2ca42008-02-19 06:12:18 +00003137 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3138 if (I.getType()->isFPOrFPVector())
3139 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003140 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003141 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003142 if (isa<UndefValue>(Op1))
3143 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003144
3145 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003146 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3147 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003148
Reid Spencer0a783f72006-11-02 01:53:59 +00003149 return 0;
3150}
3151
3152/// This function implements the transforms common to both integer remainder
3153/// instructions (urem and srem). It is called by the visitors to those integer
3154/// remainder instructions.
3155/// @brief Common integer remainder transforms
3156Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3157 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3158
3159 if (Instruction *common = commonRemTransforms(I))
3160 return common;
3161
Dale Johannesened6af242009-01-21 00:35:19 +00003162 // 0 % X == 0 for integer, we don't need to preserve faults!
3163 if (Constant *LHS = dyn_cast<Constant>(Op0))
3164 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003166
Chris Lattner857e8cd2004-12-12 21:48:58 +00003167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003168 // X % 0 == undef, we don't need to preserve faults!
3169 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003170 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003171
Chris Lattnera2881962003-02-18 19:28:33 +00003172 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003173 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003174
Chris Lattner97943922006-02-28 05:49:21 +00003175 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3176 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3177 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3178 return R;
3179 } else if (isa<PHINode>(Op0I)) {
3180 if (Instruction *NV = FoldOpIntoPhi(I))
3181 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003182 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003183
3184 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003185 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003186 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003187 }
Chris Lattnera2881962003-02-18 19:28:33 +00003188 }
3189
Reid Spencer0a783f72006-11-02 01:53:59 +00003190 return 0;
3191}
3192
3193Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3194 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3195
3196 if (Instruction *common = commonIRemTransforms(I))
3197 return common;
3198
3199 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3200 // X urem C^2 -> X and C
3201 // Check to see if this is an unsigned remainder with an exact power of 2,
3202 // if so, convert to a bitwise and.
3203 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003204 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003205 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003206 }
3207
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003208 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003209 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3210 if (RHSI->getOpcode() == Instruction::Shl &&
3211 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003212 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003213 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003214 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003215 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003216 }
3217 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003219
Reid Spencer0a783f72006-11-02 01:53:59 +00003220 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3221 // where C1&C2 are powers of two.
3222 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3223 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3224 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3225 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003226 if ((STO->getValue().isPowerOf2()) &&
3227 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003228 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3229 SI->getName()+".t");
3230 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3231 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003232 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 }
3234 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003235 }
3236
Chris Lattner3f5b8772002-05-06 16:14:14 +00003237 return 0;
3238}
3239
Reid Spencer0a783f72006-11-02 01:53:59 +00003240Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3241 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
Dan Gohmancff55092007-11-05 23:16:33 +00003243 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003244 if (Instruction *Common = commonIRemTransforms(I))
3245 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003246
Dan Gohman186a6362009-08-12 16:04:34 +00003247 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003248 if (!isa<Constant>(RHSNeg) ||
3249 (isa<ConstantInt>(RHSNeg) &&
3250 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003251 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003252 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003253 I.setOperand(1, RHSNeg);
3254 return &I;
3255 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003256
Dan Gohmancff55092007-11-05 23:16:33 +00003257 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003258 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003259 if (I.getType()->isInteger()) {
3260 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3261 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3262 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003263 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003264 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003265 }
3266
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003267 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003268 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3269 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270
Nick Lewycky9dce8732008-12-20 16:48:00 +00003271 bool hasNegative = false;
3272 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3273 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3274 if (RHS->getValue().isNegative())
3275 hasNegative = true;
3276
3277 if (hasNegative) {
3278 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003279 for (unsigned i = 0; i != VWidth; ++i) {
3280 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3281 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003282 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003283 else
3284 Elts[i] = RHS;
3285 }
3286 }
3287
Owen Andersonaf7ec972009-07-28 21:19:26 +00003288 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003289 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003290 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003291 I.setOperand(1, NewRHSV);
3292 return &I;
3293 }
3294 }
3295 }
3296
Reid Spencer0a783f72006-11-02 01:53:59 +00003297 return 0;
3298}
3299
3300Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003301 return commonRemTransforms(I);
3302}
3303
Chris Lattner457dd822004-06-09 07:59:58 +00003304// isOneBitSet - Return true if there is exactly one bit set in the specified
3305// constant.
3306static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003307 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003308}
3309
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003310// isHighOnes - Return true if the constant is of the form 1+0+.
3311// This is the same as lowones(~X).
3312static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003313 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003314}
3315
Reid Spencere4d87aa2006-12-23 06:05:41 +00003316/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003317/// are carefully arranged to allow folding of expressions such as:
3318///
3319/// (A < B) | (A > B) --> (A != B)
3320///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003321/// Note that this is only valid if the first and second predicates have the
3322/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003323///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003324/// Three bits are used to represent the condition, as follows:
3325/// 0 A > B
3326/// 1 A == B
3327/// 2 A < B
3328///
3329/// <=> Value Definition
3330/// 000 0 Always false
3331/// 001 1 A > B
3332/// 010 2 A == B
3333/// 011 3 A >= B
3334/// 100 4 A < B
3335/// 101 5 A != B
3336/// 110 6 A <= B
3337/// 111 7 Always true
3338///
3339static unsigned getICmpCode(const ICmpInst *ICI) {
3340 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003341 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003342 case ICmpInst::ICMP_UGT: return 1; // 001
3343 case ICmpInst::ICMP_SGT: return 1; // 001
3344 case ICmpInst::ICMP_EQ: return 2; // 010
3345 case ICmpInst::ICMP_UGE: return 3; // 011
3346 case ICmpInst::ICMP_SGE: return 3; // 011
3347 case ICmpInst::ICMP_ULT: return 4; // 100
3348 case ICmpInst::ICMP_SLT: return 4; // 100
3349 case ICmpInst::ICMP_NE: return 5; // 101
3350 case ICmpInst::ICMP_ULE: return 6; // 110
3351 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003352 // True -> 7
3353 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003354 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003355 return 0;
3356 }
3357}
3358
Evan Cheng8db90722008-10-14 17:15:11 +00003359/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3360/// predicate into a three bit mask. It also returns whether it is an ordered
3361/// predicate by reference.
3362static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3363 isOrdered = false;
3364 switch (CC) {
3365 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3366 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003367 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3368 case FCmpInst::FCMP_UGT: return 1; // 001
3369 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3370 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003371 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3372 case FCmpInst::FCMP_UGE: return 3; // 011
3373 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3374 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003375 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3376 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003377 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3378 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003379 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003380 default:
3381 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003382 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003383 return 0;
3384 }
3385}
3386
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387/// getICmpValue - This is the complement of getICmpCode, which turns an
3388/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003389/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003390/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003391static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003392 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003394 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003395 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396 case 1:
3397 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003398 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003400 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3401 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 case 3:
3403 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003404 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003406 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003407 case 4:
3408 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003409 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003410 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003411 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3412 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003413 case 6:
3414 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003415 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003416 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003417 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003418 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003419 }
3420}
3421
Evan Cheng8db90722008-10-14 17:15:11 +00003422/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3423/// opcode and two operands into either a FCmp instruction. isordered is passed
3424/// in to determine which kind of predicate to use in the new fcmp instruction.
3425static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003426 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003427 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003428 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003429 case 0:
3430 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003432 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003433 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003434 case 1:
3435 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003436 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003437 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003438 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003439 case 2:
3440 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003441 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003442 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003443 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003444 case 3:
3445 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003446 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003447 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003448 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003449 case 4:
3450 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003451 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003452 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003453 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003454 case 5:
3455 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003456 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003457 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003458 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003459 case 6:
3460 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003461 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003462 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003463 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003464 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003465 }
3466}
3467
Chris Lattnerb9553d62008-11-16 04:55:20 +00003468/// PredicatesFoldable - Return true if both predicates match sign or if at
3469/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003470static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3471 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003472 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3473 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003474}
3475
3476namespace {
3477// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3478struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003479 InstCombiner &IC;
3480 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 ICmpInst::Predicate pred;
3482 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3483 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3484 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003485 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003486 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3487 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003488 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3489 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003490 return false;
3491 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003492 Instruction *apply(Instruction &Log) const {
3493 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3494 if (ICI->getOperand(0) != LHS) {
3495 assert(ICI->getOperand(1) == LHS);
3496 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003497 }
3498
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003499 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003500 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003501 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502 unsigned Code;
3503 switch (Log.getOpcode()) {
3504 case Instruction::And: Code = LHSCode & RHSCode; break;
3505 case Instruction::Or: Code = LHSCode | RHSCode; break;
3506 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003507 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003508 }
3509
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003510 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3511 ICmpInst::isSignedPredicate(ICI->getPredicate());
3512
Owen Andersond672ecb2009-07-03 00:17:18 +00003513 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003514 if (Instruction *I = dyn_cast<Instruction>(RV))
3515 return I;
3516 // Otherwise, it's a constant boolean value...
3517 return IC.ReplaceInstUsesWith(Log, RV);
3518 }
3519};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003520} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003521
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3523// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003524// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003525Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003526 ConstantInt *OpRHS,
3527 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003528 BinaryOperator &TheAnd) {
3529 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003530 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003531 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003532 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003533
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534 switch (Op->getOpcode()) {
3535 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003536 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003538 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003539 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003540 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541 }
3542 break;
3543 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003544 if (Together == AndRHS) // (X | C) & C --> C
3545 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003546
Chris Lattner6e7ba452005-01-01 16:22:27 +00003547 if (Op->hasOneUse() && Together != OpRHS) {
3548 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003549 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003550 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003551 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003552 }
3553 break;
3554 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003555 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003556 // Adding a one to a single bit bit-field should be turned into an XOR
3557 // of the bit. First thing to check is to see if this AND is with a
3558 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003559 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003560
3561 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003562 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 // Ok, at this point, we know that we are masking the result of the
3564 // ADD down to exactly one bit. If the constant we are adding has
3565 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003566 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003567
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003568 // Check to see if any bits below the one bit set in AndRHSV are set.
3569 if ((AddRHS & (AndRHSV-1)) == 0) {
3570 // If not, the only thing that can effect the output of the AND is
3571 // the bit specified by AndRHSV. If that bit is set, the effect of
3572 // the XOR is to toggle the bit. If it is clear, then the ADD has
3573 // no effect.
3574 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3575 TheAnd.setOperand(0, X);
3576 return &TheAnd;
3577 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003578 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003579 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003580 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003581 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003582 }
3583 }
3584 }
3585 }
3586 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003587
3588 case Instruction::Shl: {
3589 // We know that the AND will not produce any of the bits shifted in, so if
3590 // the anded constant includes them, clear them now!
3591 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003592 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003593 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003594 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003595 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003596
Zhou Sheng290bec52007-03-29 08:15:12 +00003597 if (CI->getValue() == ShlMask) {
3598 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003599 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3600 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003601 TheAnd.setOperand(1, CI);
3602 return &TheAnd;
3603 }
3604 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003605 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003606 case Instruction::LShr:
3607 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003608 // We know that the AND will not produce any of the bits shifted in, so if
3609 // the anded constant includes them, clear them now! This only applies to
3610 // unsigned shifts, because a signed shr may bring in set bits!
3611 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003612 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003613 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003614 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003615 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003616
Zhou Sheng290bec52007-03-29 08:15:12 +00003617 if (CI->getValue() == ShrMask) {
3618 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003619 return ReplaceInstUsesWith(TheAnd, Op);
3620 } else if (CI != AndRHS) {
3621 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3622 return &TheAnd;
3623 }
3624 break;
3625 }
3626 case Instruction::AShr:
3627 // Signed shr.
3628 // See if this is shifting in some sign extension, then masking it out
3629 // with an and.
3630 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003631 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003632 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003633 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003634 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003635 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003636 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003637 // Make the argument unsigned.
3638 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003639 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003640 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003641 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003642 }
3643 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003644 }
3645 return 0;
3646}
3647
Chris Lattner8b170942002-08-09 23:47:40 +00003648
Chris Lattnera96879a2004-09-29 17:40:11 +00003649/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3650/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3652/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003653/// insert new instructions.
3654Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003655 bool isSigned, bool Inside,
3656 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003657 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003658 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003659 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660
Chris Lattnera96879a2004-09-29 17:40:11 +00003661 if (Inside) {
3662 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003663 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003664
Reid Spencere4d87aa2006-12-23 06:05:41 +00003665 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003666 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003667 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003669 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 }
3671
3672 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003673 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003674 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003675 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003676 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003677 }
3678
3679 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003680 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003681
Reid Spencere4e40032007-03-21 23:19:50 +00003682 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003683 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003684 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 ICmpInst::Predicate pred = (isSigned ?
3686 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003687 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003688 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003689
Reid Spencere4e40032007-03-21 23:19:50 +00003690 // Emit V-Lo >u Hi-1-Lo
3691 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003692 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003693 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003694 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003695 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003696}
3697
Chris Lattner7203e152005-09-18 07:22:02 +00003698// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3699// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3700// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3701// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003702static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003703 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003704 uint32_t BitWidth = Val->getType()->getBitWidth();
3705 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003706
3707 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003708 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003709 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003710 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003711 return true;
3712}
3713
Chris Lattner7203e152005-09-18 07:22:02 +00003714/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3715/// where isSub determines whether the operator is a sub. If we can fold one of
3716/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003717///
3718/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3719/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3720/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3721///
3722/// return (A +/- B).
3723///
3724Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003725 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003726 Instruction &I) {
3727 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3728 if (!LHSI || LHSI->getNumOperands() != 2 ||
3729 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3730
3731 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3732
3733 switch (LHSI->getOpcode()) {
3734 default: return 0;
3735 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003736 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003737 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003738 if ((Mask->getValue().countLeadingZeros() +
3739 Mask->getValue().countPopulation()) ==
3740 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003741 break;
3742
3743 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3744 // part, we don't need any explicit masks to take them out of A. If that
3745 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003746 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003747 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003748 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003749 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003750 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003751 break;
3752 }
3753 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754 return 0;
3755 case Instruction::Or:
3756 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003757 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003758 if ((Mask->getValue().countLeadingZeros() +
3759 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003760 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003761 break;
3762 return 0;
3763 }
3764
Chris Lattnerc8e77562005-09-18 04:24:45 +00003765 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003766 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3767 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003768}
3769
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003770/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3771Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3772 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003773 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003774 ConstantInt *LHSCst, *RHSCst;
3775 ICmpInst::Predicate LHSCC, RHSCC;
3776
Chris Lattnerea065fb2008-11-16 05:10:52 +00003777 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003778 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003779 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003780 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003781 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003782 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003783
3784 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3785 // where C is a power of 2
3786 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3787 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003788 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003789 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003790 }
3791
3792 // From here on, we only handle:
3793 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3794 if (Val != Val2) return 0;
3795
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003796 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3797 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3798 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3799 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3800 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3801 return 0;
3802
3803 // We can't fold (ugt x, C) & (sgt x, C2).
3804 if (!PredicatesFoldable(LHSCC, RHSCC))
3805 return 0;
3806
3807 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003808 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003809 if (ICmpInst::isSignedPredicate(LHSCC) ||
3810 (ICmpInst::isEquality(LHSCC) &&
3811 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003812 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003813 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003814 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3815
3816 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003817 std::swap(LHS, RHS);
3818 std::swap(LHSCst, RHSCst);
3819 std::swap(LHSCC, RHSCC);
3820 }
3821
3822 // At this point, we know we have have two icmp instructions
3823 // comparing a value against two constants and and'ing the result
3824 // together. Because of the above check, we know that we only have
3825 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3826 // (from the FoldICmpLogical check above), that the two constants
3827 // are not equal and that the larger constant is on the RHS
3828 assert(LHSCst != RHSCst && "Compares not folded above?");
3829
3830 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003831 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003832 case ICmpInst::ICMP_EQ:
3833 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003834 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003835 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3836 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3837 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003838 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003839 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3840 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3841 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3842 return ReplaceInstUsesWith(I, LHS);
3843 }
3844 case ICmpInst::ICMP_NE:
3845 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003846 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003847 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003848 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003849 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003850 break; // (X != 13 & X u< 15) -> no change
3851 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003852 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003853 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003854 break; // (X != 13 & X s< 15) -> no change
3855 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3856 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3857 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3858 return ReplaceInstUsesWith(I, RHS);
3859 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003860 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003861 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003862 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003863 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003864 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003865 }
3866 break; // (X != 13 & X != 15) -> no change
3867 }
3868 break;
3869 case ICmpInst::ICMP_ULT:
3870 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003871 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003872 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3873 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003874 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003875 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3876 break;
3877 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3878 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3879 return ReplaceInstUsesWith(I, LHS);
3880 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3881 break;
3882 }
3883 break;
3884 case ICmpInst::ICMP_SLT:
3885 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003886 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003887 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3888 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003890 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3891 break;
3892 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3893 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3894 return ReplaceInstUsesWith(I, LHS);
3895 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3896 break;
3897 }
3898 break;
3899 case ICmpInst::ICMP_UGT:
3900 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003901 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3903 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3904 return ReplaceInstUsesWith(I, RHS);
3905 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3906 break;
3907 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003908 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003909 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003910 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003911 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003912 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003913 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3915 break;
3916 }
3917 break;
3918 case ICmpInst::ICMP_SGT:
3919 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003920 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003921 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3922 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3923 return ReplaceInstUsesWith(I, RHS);
3924 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3925 break;
3926 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003927 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003928 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003929 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003930 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003931 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003932 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003933 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3934 break;
3935 }
3936 break;
3937 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003938
3939 return 0;
3940}
3941
Chris Lattner42d1be02009-07-23 05:14:02 +00003942Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3943 FCmpInst *RHS) {
3944
3945 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3946 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3947 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3948 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3949 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3950 // If either of the constants are nans, then the whole thing returns
3951 // false.
3952 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003953 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003954 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003955 LHS->getOperand(0), RHS->getOperand(0));
3956 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003957
3958 // Handle vector zeros. This occurs because the canonical form of
3959 // "fcmp ord x,x" is "fcmp ord x, 0".
3960 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3961 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003962 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003963 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003964 return 0;
3965 }
3966
3967 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3968 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3969 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3970
3971
3972 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3973 // Swap RHS operands to match LHS.
3974 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3975 std::swap(Op1LHS, Op1RHS);
3976 }
3977
3978 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3979 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3980 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003981 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003982
3983 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003984 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003985 if (Op0CC == FCmpInst::FCMP_TRUE)
3986 return ReplaceInstUsesWith(I, RHS);
3987 if (Op1CC == FCmpInst::FCMP_TRUE)
3988 return ReplaceInstUsesWith(I, LHS);
3989
3990 bool Op0Ordered;
3991 bool Op1Ordered;
3992 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3993 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3994 if (Op1Pred == 0) {
3995 std::swap(LHS, RHS);
3996 std::swap(Op0Pred, Op1Pred);
3997 std::swap(Op0Ordered, Op1Ordered);
3998 }
3999 if (Op0Pred == 0) {
4000 // uno && ueq -> uno && (uno || eq) -> ueq
4001 // ord && olt -> ord && (ord && lt) -> olt
4002 if (Op0Ordered == Op1Ordered)
4003 return ReplaceInstUsesWith(I, RHS);
4004
4005 // uno && oeq -> uno && (ord && eq) -> false
4006 // uno && ord -> false
4007 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004008 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004009 // ord && ueq -> ord && (uno || eq) -> oeq
4010 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4011 Op0LHS, Op0RHS, Context));
4012 }
4013 }
4014
4015 return 0;
4016}
4017
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004018
Chris Lattner7e708292002-06-25 16:13:24 +00004019Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004020 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004022
Chris Lattnere87597f2004-10-16 18:11:37 +00004023 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004024 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004025
Chris Lattner6e7ba452005-01-01 16:22:27 +00004026 // and X, X = X
4027 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004028 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004029
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004030 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004031 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004032 if (SimplifyDemandedInstructionBits(I))
4033 return &I;
4034 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004035 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004036 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004037 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004038 } else if (isa<ConstantAggregateZero>(Op1)) {
4039 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004040 }
4041 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004042
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004043 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004044 const APInt& AndRHSMask = AndRHS->getValue();
4045 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004046
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004047 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004048 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004049 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004050 Value *Op0LHS = Op0I->getOperand(0);
4051 Value *Op0RHS = Op0I->getOperand(1);
4052 switch (Op0I->getOpcode()) {
4053 case Instruction::Xor:
4054 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004055 // If the mask is only needed on one incoming arm, push it up.
4056 if (Op0I->hasOneUse()) {
4057 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4058 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004059 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4060 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004061 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004062 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004063 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004064 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004065 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4066 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004067 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4068 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004069 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004070 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4071 }
4072 }
4073
Chris Lattner6e7ba452005-01-01 16:22:27 +00004074 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004075 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004076 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4077 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4078 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4079 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004080 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004081 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004082 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004083 break;
4084
4085 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004086 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4087 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4088 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4089 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004091
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004092 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4093 // has 1's for all bits that the subtraction with A might affect.
4094 if (Op0I->hasOneUse()) {
4095 uint32_t BitWidth = AndRHSMask.getBitWidth();
4096 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4097 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4098
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004099 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004100 if (!(A && A->isZero()) && // avoid infinite recursion.
4101 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004102 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004103 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4104 }
4105 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004106 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004107
4108 case Instruction::Shl:
4109 case Instruction::LShr:
4110 // (1 << x) & 1 --> zext(x == 0)
4111 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004112 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004113 Value *NewICmp =
4114 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004115 return new ZExtInst(NewICmp, I.getType());
4116 }
4117 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004118 }
4119
Chris Lattner58403262003-07-23 19:25:52 +00004120 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004121 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004122 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004123 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004124 // If this is an integer truncation or change from signed-to-unsigned, and
4125 // if the source is an and/or with immediate, transform it. This
4126 // frequently occurs for bitfield accesses.
4127 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004128 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004129 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004130 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004131 if (CastOp->getOpcode() == Instruction::And) {
4132 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004133 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4134 // This will fold the two constants together, which may allow
4135 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004136 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004137 CastOp->getOperand(0), I.getType(),
4138 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004139 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004140 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004141 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004142 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004143 } else if (CastOp->getOpcode() == Instruction::Or) {
4144 // Change: and (cast (or X, C1) to T), C2
4145 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004146 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004147 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004148 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004149 return ReplaceInstUsesWith(I, AndRHS);
4150 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004151 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004152 }
Chris Lattner06782f82003-07-23 19:36:21 +00004153 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004154
4155 // Try to fold constant and into select arguments.
4156 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004157 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004158 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004159 if (isa<PHINode>(Op0))
4160 if (Instruction *NV = FoldOpIntoPhi(I))
4161 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004162 }
4163
Dan Gohman186a6362009-08-12 16:04:34 +00004164 Value *Op0NotVal = dyn_castNotVal(Op0);
4165 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004166
Chris Lattner5b62aa72004-06-18 06:07:51 +00004167 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004168 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004169
Misha Brukmancb6267b2004-07-30 12:50:08 +00004170 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004171 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004172 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4173 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004174 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004175 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004176
4177 {
Chris Lattner003b6202007-06-15 05:58:24 +00004178 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004179 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004180 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4181 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004182
4183 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004184 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004185 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004186 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004187 }
4188 }
4189
Dan Gohman4ae51262009-08-12 16:23:25 +00004190 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004191 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4192 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004193
4194 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004195 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004196 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004197 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004198 }
4199 }
Chris Lattner64daab52006-04-01 08:03:55 +00004200
4201 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004202 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004203 if (A == Op1) { // (A^B)&A -> A&(A^B)
4204 I.swapOperands(); // Simplify below
4205 std::swap(Op0, Op1);
4206 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4207 cast<BinaryOperator>(Op0)->swapOperands();
4208 I.swapOperands(); // Simplify below
4209 std::swap(Op0, Op1);
4210 }
4211 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004212
Chris Lattner64daab52006-04-01 08:03:55 +00004213 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004214 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004215 if (B == Op0) { // B&(A^B) -> B&(B^A)
4216 cast<BinaryOperator>(Op1)->swapOperands();
4217 std::swap(A, B);
4218 }
Chris Lattner74381062009-08-30 07:44:24 +00004219 if (A == Op0) // A&(A^B) -> A & ~B
4220 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004221 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004222
4223 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004224 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4225 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004226 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004227 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4228 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004229 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004230 }
4231
Reid Spencere4d87aa2006-12-23 06:05:41 +00004232 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4233 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004234 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004235 return R;
4236
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004237 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4238 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4239 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004240 }
4241
Chris Lattner6fc205f2006-05-05 06:39:07 +00004242 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004243 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4244 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4245 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4246 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004247 if (SrcTy == Op1C->getOperand(0)->getType() &&
4248 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004249 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004250 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4251 I.getType(), TD) &&
4252 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4253 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004254 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4255 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004256 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004257 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004258 }
Chris Lattnere511b742006-11-14 07:46:50 +00004259
4260 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004261 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4262 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4263 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004264 SI0->getOperand(1) == SI1->getOperand(1) &&
4265 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004266 Value *NewOp =
4267 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4268 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004269 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004270 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004271 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004272 }
4273
Evan Cheng8db90722008-10-14 17:15:11 +00004274 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004275 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004276 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4277 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4278 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004279 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004280
Chris Lattner7e708292002-06-25 16:13:24 +00004281 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004282}
4283
Chris Lattner8c34cd22008-10-05 02:13:19 +00004284/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4285/// capable of providing pieces of a bswap. The subexpression provides pieces
4286/// of a bswap if it is proven that each of the non-zero bytes in the output of
4287/// the expression came from the corresponding "byte swapped" byte in some other
4288/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4289/// we know that the expression deposits the low byte of %X into the high byte
4290/// of the bswap result and that all other bytes are zero. This expression is
4291/// accepted, the high byte of ByteValues is set to X to indicate a correct
4292/// match.
4293///
4294/// This function returns true if the match was unsuccessful and false if so.
4295/// On entry to the function the "OverallLeftShift" is a signed integer value
4296/// indicating the number of bytes that the subexpression is later shifted. For
4297/// example, if the expression is later right shifted by 16 bits, the
4298/// OverallLeftShift value would be -2 on entry. This is used to specify which
4299/// byte of ByteValues is actually being set.
4300///
4301/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4302/// byte is masked to zero by a user. For example, in (X & 255), X will be
4303/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4304/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4305/// always in the local (OverallLeftShift) coordinate space.
4306///
4307static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4308 SmallVector<Value*, 8> &ByteValues) {
4309 if (Instruction *I = dyn_cast<Instruction>(V)) {
4310 // If this is an or instruction, it may be an inner node of the bswap.
4311 if (I->getOpcode() == Instruction::Or) {
4312 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4313 ByteValues) ||
4314 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4315 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004316 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004317
4318 // If this is a logical shift by a constant multiple of 8, recurse with
4319 // OverallLeftShift and ByteMask adjusted.
4320 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4321 unsigned ShAmt =
4322 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4323 // Ensure the shift amount is defined and of a byte value.
4324 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4325 return true;
4326
4327 unsigned ByteShift = ShAmt >> 3;
4328 if (I->getOpcode() == Instruction::Shl) {
4329 // X << 2 -> collect(X, +2)
4330 OverallLeftShift += ByteShift;
4331 ByteMask >>= ByteShift;
4332 } else {
4333 // X >>u 2 -> collect(X, -2)
4334 OverallLeftShift -= ByteShift;
4335 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004336 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004337 }
4338
4339 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4340 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4341
4342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4343 ByteValues);
4344 }
4345
4346 // If this is a logical 'and' with a mask that clears bytes, clear the
4347 // corresponding bytes in ByteMask.
4348 if (I->getOpcode() == Instruction::And &&
4349 isa<ConstantInt>(I->getOperand(1))) {
4350 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4351 unsigned NumBytes = ByteValues.size();
4352 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4353 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4354
4355 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4356 // If this byte is masked out by a later operation, we don't care what
4357 // the and mask is.
4358 if ((ByteMask & (1 << i)) == 0)
4359 continue;
4360
4361 // If the AndMask is all zeros for this byte, clear the bit.
4362 APInt MaskB = AndMask & Byte;
4363 if (MaskB == 0) {
4364 ByteMask &= ~(1U << i);
4365 continue;
4366 }
4367
4368 // If the AndMask is not all ones for this byte, it's not a bytezap.
4369 if (MaskB != Byte)
4370 return true;
4371
4372 // Otherwise, this byte is kept.
4373 }
4374
4375 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4376 ByteValues);
4377 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004378 }
4379
Chris Lattner8c34cd22008-10-05 02:13:19 +00004380 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4381 // the input value to the bswap. Some observations: 1) if more than one byte
4382 // is demanded from this input, then it could not be successfully assembled
4383 // into a byteswap. At least one of the two bytes would not be aligned with
4384 // their ultimate destination.
4385 if (!isPowerOf2_32(ByteMask)) return true;
4386 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387
Chris Lattner8c34cd22008-10-05 02:13:19 +00004388 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4389 // is demanded, it needs to go into byte 0 of the result. This means that the
4390 // byte needs to be shifted until it lands in the right byte bucket. The
4391 // shift amount depends on the position: if the byte is coming from the high
4392 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4393 // low part, it must be shifted left.
4394 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4395 if (InputByteNo < ByteValues.size()/2) {
4396 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4397 return true;
4398 } else {
4399 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4400 return true;
4401 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004402
4403 // If the destination byte value is already defined, the values are or'd
4404 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004405 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004407 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004408 return false;
4409}
4410
4411/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4412/// If so, insert the new bswap intrinsic and return it.
4413Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004414 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004415 if (!ITy || ITy->getBitWidth() % 16 ||
4416 // ByteMask only allows up to 32-byte values.
4417 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004418 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004419
4420 /// ByteValues - For each byte of the result, we keep track of which value
4421 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004422 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004423 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004424
4425 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004426 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4427 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 return 0;
4429
4430 // Check to see if all of the bytes come from the same value.
4431 Value *V = ByteValues[0];
4432 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4433
4434 // Check to make sure that all of the bytes come from the same value.
4435 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4436 if (ByteValues[i] != V)
4437 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004438 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004439 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004440 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004441 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442}
4443
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004444/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4445/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4446/// we can simplify this expression to "cond ? C : D or B".
4447static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004448 Value *C, Value *D,
4449 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004450 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004451 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004452 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004453 return 0;
4454
Chris Lattnera6a474d2008-11-16 04:26:55 +00004455 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004456 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004457 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004458 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004459 return SelectInst::Create(Cond, C, B);
4460 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004461 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004462 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004463 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004464 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004465 return 0;
4466}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004467
Chris Lattner69d4ced2008-11-16 05:20:07 +00004468/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4469Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4470 ICmpInst *LHS, ICmpInst *RHS) {
4471 Value *Val, *Val2;
4472 ConstantInt *LHSCst, *RHSCst;
4473 ICmpInst::Predicate LHSCC, RHSCC;
4474
4475 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004476 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004477 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004478 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004479 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004480 return 0;
4481
4482 // From here on, we only handle:
4483 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4484 if (Val != Val2) return 0;
4485
4486 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4487 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4488 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4489 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4490 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4491 return 0;
4492
4493 // We can't fold (ugt x, C) | (sgt x, C2).
4494 if (!PredicatesFoldable(LHSCC, RHSCC))
4495 return 0;
4496
4497 // Ensure that the larger constant is on the RHS.
4498 bool ShouldSwap;
4499 if (ICmpInst::isSignedPredicate(LHSCC) ||
4500 (ICmpInst::isEquality(LHSCC) &&
4501 ICmpInst::isSignedPredicate(RHSCC)))
4502 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4503 else
4504 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4505
4506 if (ShouldSwap) {
4507 std::swap(LHS, RHS);
4508 std::swap(LHSCst, RHSCst);
4509 std::swap(LHSCC, RHSCC);
4510 }
4511
4512 // At this point, we know we have have two icmp instructions
4513 // comparing a value against two constants and or'ing the result
4514 // together. Because of the above check, we know that we only have
4515 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4516 // FoldICmpLogical check above), that the two constants are not
4517 // equal.
4518 assert(LHSCst != RHSCst && "Compares not folded above?");
4519
4520 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004521 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004522 case ICmpInst::ICMP_EQ:
4523 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004524 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004525 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004526 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004527 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004528 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004529 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004530 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004531 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004532 }
4533 break; // (X == 13 | X == 15) -> no change
4534 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4535 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4536 break;
4537 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4538 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4539 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4540 return ReplaceInstUsesWith(I, RHS);
4541 }
4542 break;
4543 case ICmpInst::ICMP_NE:
4544 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004545 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004546 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4547 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4548 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4549 return ReplaceInstUsesWith(I, LHS);
4550 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4551 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4552 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004553 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004554 }
4555 break;
4556 case ICmpInst::ICMP_ULT:
4557 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004558 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004559 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4560 break;
4561 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4562 // If RHSCst is [us]MAXINT, it is always false. Not handling
4563 // this can cause overflow.
4564 if (RHSCst->isMaxValue(false))
4565 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004566 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004567 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004568 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4569 break;
4570 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4571 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4572 return ReplaceInstUsesWith(I, RHS);
4573 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4574 break;
4575 }
4576 break;
4577 case ICmpInst::ICMP_SLT:
4578 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004579 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4581 break;
4582 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4583 // If RHSCst is [us]MAXINT, it is always false. Not handling
4584 // this can cause overflow.
4585 if (RHSCst->isMaxValue(true))
4586 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004587 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004588 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004589 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4590 break;
4591 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4592 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4593 return ReplaceInstUsesWith(I, RHS);
4594 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4595 break;
4596 }
4597 break;
4598 case ICmpInst::ICMP_UGT:
4599 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004600 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004601 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4602 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4603 return ReplaceInstUsesWith(I, LHS);
4604 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4605 break;
4606 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4607 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004608 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004609 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4610 break;
4611 }
4612 break;
4613 case ICmpInst::ICMP_SGT:
4614 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004615 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004616 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4617 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4618 return ReplaceInstUsesWith(I, LHS);
4619 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4620 break;
4621 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4622 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004623 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004624 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4625 break;
4626 }
4627 break;
4628 }
4629 return 0;
4630}
4631
Chris Lattner5414cc52009-07-23 05:46:22 +00004632Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4633 FCmpInst *RHS) {
4634 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4635 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4636 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4637 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4638 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4639 // If either of the constants are nans, then the whole thing returns
4640 // true.
4641 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004642 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004643
4644 // Otherwise, no need to compare the two constants, compare the
4645 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004646 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004647 LHS->getOperand(0), RHS->getOperand(0));
4648 }
4649
4650 // Handle vector zeros. This occurs because the canonical form of
4651 // "fcmp uno x,x" is "fcmp uno x, 0".
4652 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4653 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004654 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004655 LHS->getOperand(0), RHS->getOperand(0));
4656
4657 return 0;
4658 }
4659
4660 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4661 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4662 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4663
4664 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4665 // Swap RHS operands to match LHS.
4666 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4667 std::swap(Op1LHS, Op1RHS);
4668 }
4669 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4670 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4671 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004672 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004673 Op0LHS, Op0RHS);
4674 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004675 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004676 if (Op0CC == FCmpInst::FCMP_FALSE)
4677 return ReplaceInstUsesWith(I, RHS);
4678 if (Op1CC == FCmpInst::FCMP_FALSE)
4679 return ReplaceInstUsesWith(I, LHS);
4680 bool Op0Ordered;
4681 bool Op1Ordered;
4682 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4683 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4684 if (Op0Ordered == Op1Ordered) {
4685 // If both are ordered or unordered, return a new fcmp with
4686 // or'ed predicates.
4687 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4688 Op0LHS, Op0RHS, Context);
4689 if (Instruction *I = dyn_cast<Instruction>(RV))
4690 return I;
4691 // Otherwise, it's a constant boolean value...
4692 return ReplaceInstUsesWith(I, RV);
4693 }
4694 }
4695 return 0;
4696}
4697
Bill Wendlinga698a472008-12-01 08:23:25 +00004698/// FoldOrWithConstants - This helper function folds:
4699///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004700/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004701///
4702/// into:
4703///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004704/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004705///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004706/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004707Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004708 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004709 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4710 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004711
Bill Wendling286a0542008-12-02 06:24:20 +00004712 Value *V1 = 0;
4713 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004714 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004715
Bill Wendling29976b92008-12-02 06:18:11 +00004716 APInt Xor = CI1->getValue() ^ CI2->getValue();
4717 if (!Xor.isAllOnesValue()) return 0;
4718
Bill Wendling286a0542008-12-02 06:24:20 +00004719 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004720 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004721 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004722 }
4723
4724 return 0;
4725}
4726
Chris Lattner7e708292002-06-25 16:13:24 +00004727Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004728 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004730
Chris Lattner42593e62007-03-24 23:56:43 +00004731 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004732 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004733
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004734 // or X, X = X
4735 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004736 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004737
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004738 // See if we can simplify any instructions used by the instruction whose sole
4739 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004740 if (SimplifyDemandedInstructionBits(I))
4741 return &I;
4742 if (isa<VectorType>(I.getType())) {
4743 if (isa<ConstantAggregateZero>(Op1)) {
4744 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4745 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4746 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4747 return ReplaceInstUsesWith(I, I.getOperand(1));
4748 }
Chris Lattner42593e62007-03-24 23:56:43 +00004749 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004750
Chris Lattner3f5b8772002-05-06 16:14:14 +00004751 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004752 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004753 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004754 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004755 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004756 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004757 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004758 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004759 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004760 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004761 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004762
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004763 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004764 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004765 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004766 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004767 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004768 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004769 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004770 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004771
4772 // Try to fold constant and into select arguments.
4773 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004774 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004775 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004776 if (isa<PHINode>(Op0))
4777 if (Instruction *NV = FoldOpIntoPhi(I))
4778 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004779 }
4780
Chris Lattner4f637d42006-01-06 17:59:59 +00004781 Value *A = 0, *B = 0;
4782 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004783
Dan Gohman4ae51262009-08-12 16:23:25 +00004784 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004785 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4786 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004787 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004788 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4789 return ReplaceInstUsesWith(I, Op0);
4790
Chris Lattner6423d4c2006-07-10 20:25:24 +00004791 // (A | B) | C and A | (B | C) -> bswap if possible.
4792 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004793 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4794 match(Op1, m_Or(m_Value(), m_Value())) ||
4795 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4796 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004797 if (Instruction *BSwap = MatchBSwap(I))
4798 return BSwap;
4799 }
4800
Chris Lattner6e4c6492005-05-09 04:58:36 +00004801 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004802 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004803 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004804 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004805 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004806 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004807 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004808 }
4809
4810 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004811 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004812 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004813 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004814 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004815 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004816 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004817 }
4818
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004819 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004820 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004821 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4822 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004823 Value *V1 = 0, *V2 = 0, *V3 = 0;
4824 C1 = dyn_cast<ConstantInt>(C);
4825 C2 = dyn_cast<ConstantInt>(D);
4826 if (C1 && C2) { // (A & C1)|(B & C2)
4827 // If we have: ((V + N) & C1) | (V & C2)
4828 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4829 // replace with V+N.
4830 if (C1->getValue() == ~C2->getValue()) {
4831 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004832 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004833 // Add commutes, try both ways.
4834 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4835 return ReplaceInstUsesWith(I, A);
4836 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4837 return ReplaceInstUsesWith(I, A);
4838 }
4839 // Or commutes, try both ways.
4840 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004841 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004842 // Add commutes, try both ways.
4843 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4844 return ReplaceInstUsesWith(I, B);
4845 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4846 return ReplaceInstUsesWith(I, B);
4847 }
4848 }
Chris Lattner044e5332007-04-08 08:01:49 +00004849 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004850 }
4851
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004852 // Check to see if we have any common things being and'ed. If so, find the
4853 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004854 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4855 if (A == B) // (A & C)|(A & D) == A & (C|D)
4856 V1 = A, V2 = C, V3 = D;
4857 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4858 V1 = A, V2 = B, V3 = C;
4859 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4860 V1 = C, V2 = A, V3 = D;
4861 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4862 V1 = C, V2 = A, V3 = B;
4863
4864 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004865 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004866 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004867 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004868 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004869
Dan Gohman1975d032008-10-30 20:40:10 +00004870 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004871 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004872 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004873 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004874 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004875 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004876 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004877 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004878 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004879
Bill Wendlingb01865c2008-11-30 13:52:49 +00004880 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004881 if ((match(C, m_Not(m_Specific(D))) &&
4882 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004883 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004884 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004885 if ((match(A, m_Not(m_Specific(D))) &&
4886 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004887 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004888 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004889 if ((match(C, m_Not(m_Specific(B))) &&
4890 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004891 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004892 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004893 if ((match(A, m_Not(m_Specific(B))) &&
4894 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004895 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004896 }
Chris Lattnere511b742006-11-14 07:46:50 +00004897
4898 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004899 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4900 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4901 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004902 SI0->getOperand(1) == SI1->getOperand(1) &&
4903 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004904 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4905 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004906 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004907 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004908 }
4909 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004910
Bill Wendlingb3833d12008-12-01 01:07:11 +00004911 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004912 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4913 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004914 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004915 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004916 }
4917 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004918 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4919 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004920 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004921 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004922 }
4923
Dan Gohman4ae51262009-08-12 16:23:25 +00004924 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004925 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004926 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004927 } else {
4928 A = 0;
4929 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004930 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004931 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004932 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004933 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004934
Misha Brukmancb6267b2004-07-30 12:50:08 +00004935 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004936 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004937 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004938 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004939 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004940 }
Chris Lattnera2881962003-02-18 19:28:33 +00004941
Reid Spencere4d87aa2006-12-23 06:05:41 +00004942 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4943 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004944 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004945 return R;
4946
Chris Lattner69d4ced2008-11-16 05:20:07 +00004947 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4948 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4949 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004950 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004951
4952 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004953 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004954 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004955 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004956 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4957 !isa<ICmpInst>(Op1C->getOperand(0))) {
4958 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004959 if (SrcTy == Op1C->getOperand(0)->getType() &&
4960 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004961 // Only do this if the casts both really cause code to be
4962 // generated.
4963 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4964 I.getType(), TD) &&
4965 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4966 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004967 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4968 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004969 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004970 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004971 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004972 }
Chris Lattner99c65742007-10-24 05:38:08 +00004973 }
4974
4975
4976 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4977 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004978 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4979 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4980 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004981 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004982
Chris Lattner7e708292002-06-25 16:13:24 +00004983 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004984}
4985
Dan Gohman844731a2008-05-13 00:00:25 +00004986namespace {
4987
Chris Lattnerc317d392004-02-16 01:20:27 +00004988// XorSelf - Implements: X ^ X --> 0
4989struct XorSelf {
4990 Value *RHS;
4991 XorSelf(Value *rhs) : RHS(rhs) {}
4992 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4993 Instruction *apply(BinaryOperator &Xor) const {
4994 return &Xor;
4995 }
4996};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004997
Dan Gohman844731a2008-05-13 00:00:25 +00004998}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004999
Chris Lattner7e708292002-06-25 16:13:24 +00005000Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005001 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005002 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005003
Evan Chengd34af782008-03-25 20:07:13 +00005004 if (isa<UndefValue>(Op1)) {
5005 if (isa<UndefValue>(Op0))
5006 // Handle undef ^ undef -> 0 special case. This is a common
5007 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005008 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005009 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005010 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005011
Chris Lattnerc317d392004-02-16 01:20:27 +00005012 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005013 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005014 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005016 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005017
5018 // See if we can simplify any instructions used by the instruction whose sole
5019 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005020 if (SimplifyDemandedInstructionBits(I))
5021 return &I;
5022 if (isa<VectorType>(I.getType()))
5023 if (isa<ConstantAggregateZero>(Op1))
5024 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005025
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005026 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005027 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005028 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5029 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5030 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5031 if (Op0I->getOpcode() == Instruction::And ||
5032 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005033 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5034 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005035 Value *NotY =
5036 Builder->CreateNot(Op0I->getOperand(1),
5037 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005038 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005039 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005040 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005041 }
5042 }
5043 }
5044 }
5045
5046
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005047 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005048 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005049 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005050 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005051 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005052 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005053
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005054 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005055 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005056 FCI->getOperand(0), FCI->getOperand(1));
5057 }
5058
Nick Lewycky517e1f52008-05-31 19:01:33 +00005059 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5060 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5061 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5062 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5063 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005064 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5065 (RHS == ConstantExpr::getCast(Opcode,
5066 ConstantInt::getTrue(*Context),
5067 Op0C->getDestTy()))) {
5068 CI->setPredicate(CI->getInversePredicate());
5069 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005070 }
5071 }
5072 }
5073 }
5074
Reid Spencere4d87aa2006-12-23 06:05:41 +00005075 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005076 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005077 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5078 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005079 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5080 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005081 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005082 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005083 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005084
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005085 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005086 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005087 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005088 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005089 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005090 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005091 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005092 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005093 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005094 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005095 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005096 Constant *C = ConstantInt::get(*Context,
5097 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005098 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005099
Chris Lattner7c4049c2004-01-12 19:35:11 +00005100 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005101 } else if (Op0I->getOpcode() == Instruction::Or) {
5102 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005103 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005104 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005105 // Anything in both C1 and C2 is known to be zero, remove it from
5106 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005107 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5108 NewRHS = ConstantExpr::getAnd(NewRHS,
5109 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005110 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005111 I.setOperand(0, Op0I->getOperand(0));
5112 I.setOperand(1, NewRHS);
5113 return &I;
5114 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005115 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005116 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005117 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005118
5119 // Try to fold constant and into select arguments.
5120 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005121 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005122 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005123 if (isa<PHINode>(Op0))
5124 if (Instruction *NV = FoldOpIntoPhi(I))
5125 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005126 }
5127
Dan Gohman186a6362009-08-12 16:04:34 +00005128 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005129 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005130 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005131
Dan Gohman186a6362009-08-12 16:04:34 +00005132 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005133 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005134 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005135
Chris Lattner318bf792007-03-18 22:51:34 +00005136
5137 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5138 if (Op1I) {
5139 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005140 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005141 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005142 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005143 I.swapOperands();
5144 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005145 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005146 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005147 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005148 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005149 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005150 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005151 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005152 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005153 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005154 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005155 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005156 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005157 std::swap(A, B);
5158 }
Chris Lattner318bf792007-03-18 22:51:34 +00005159 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005160 I.swapOperands(); // Simplified below.
5161 std::swap(Op0, Op1);
5162 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005163 }
Chris Lattner318bf792007-03-18 22:51:34 +00005164 }
5165
5166 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5167 if (Op0I) {
5168 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005169 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005170 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005171 if (A == Op1) // (B|A)^B == (A|B)^B
5172 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005173 if (B == Op1) // (A|B)^B == A & ~B
5174 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005175 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005176 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005177 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005178 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005179 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005180 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005181 if (A == Op1) // (A&B)^A -> (B&A)^A
5182 std::swap(A, B);
5183 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005184 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005185 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005186 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005187 }
Chris Lattner318bf792007-03-18 22:51:34 +00005188 }
5189
5190 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5191 if (Op0I && Op1I && Op0I->isShift() &&
5192 Op0I->getOpcode() == Op1I->getOpcode() &&
5193 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5194 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005195 Value *NewOp =
5196 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5197 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005198 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005199 Op1I->getOperand(1));
5200 }
5201
5202 if (Op0I && Op1I) {
5203 Value *A, *B, *C, *D;
5204 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005205 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5206 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005207 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005208 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005209 }
5210 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005211 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5212 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005213 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005214 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005215 }
5216
5217 // (A & B)^(C & D)
5218 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005219 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5220 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005221 // (X & Y)^(X & Y) -> (Y^Z) & X
5222 Value *X = 0, *Y = 0, *Z = 0;
5223 if (A == C)
5224 X = A, Y = B, Z = D;
5225 else if (A == D)
5226 X = A, Y = B, Z = C;
5227 else if (B == C)
5228 X = B, Y = A, Z = D;
5229 else if (B == D)
5230 X = B, Y = A, Z = C;
5231
5232 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005233 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005234 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005235 }
5236 }
5237 }
5238
Reid Spencere4d87aa2006-12-23 06:05:41 +00005239 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5240 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005241 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005242 return R;
5243
Chris Lattner6fc205f2006-05-05 06:39:07 +00005244 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005245 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005246 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005247 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5248 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005249 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005250 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005251 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5252 I.getType(), TD) &&
5253 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5254 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005255 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5256 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005257 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005258 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005259 }
Chris Lattner99c65742007-10-24 05:38:08 +00005260 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005261
Chris Lattner7e708292002-06-25 16:13:24 +00005262 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005263}
5264
Owen Andersond672ecb2009-07-03 00:17:18 +00005265static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005266 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005267 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005268}
Chris Lattnera96879a2004-09-29 17:40:11 +00005269
Dan Gohman6de29f82009-06-15 22:12:54 +00005270static bool HasAddOverflow(ConstantInt *Result,
5271 ConstantInt *In1, ConstantInt *In2,
5272 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005273 if (IsSigned)
5274 if (In2->getValue().isNegative())
5275 return Result->getValue().sgt(In1->getValue());
5276 else
5277 return Result->getValue().slt(In1->getValue());
5278 else
5279 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005280}
5281
Dan Gohman6de29f82009-06-15 22:12:54 +00005282/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005283/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005284static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005285 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005286 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005287 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005288
Dan Gohman6de29f82009-06-15 22:12:54 +00005289 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5290 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005291 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005292 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5293 ExtractElement(In1, Idx, Context),
5294 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005295 IsSigned))
5296 return true;
5297 }
5298 return false;
5299 }
5300
5301 return HasAddOverflow(cast<ConstantInt>(Result),
5302 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5303 IsSigned);
5304}
5305
5306static bool HasSubOverflow(ConstantInt *Result,
5307 ConstantInt *In1, ConstantInt *In2,
5308 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005309 if (IsSigned)
5310 if (In2->getValue().isNegative())
5311 return Result->getValue().slt(In1->getValue());
5312 else
5313 return Result->getValue().sgt(In1->getValue());
5314 else
5315 return Result->getValue().ugt(In1->getValue());
5316}
5317
Dan Gohman6de29f82009-06-15 22:12:54 +00005318/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5319/// overflowed for this type.
5320static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005321 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005322 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005323 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005324
5325 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5326 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005327 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005328 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5329 ExtractElement(In1, Idx, Context),
5330 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005331 IsSigned))
5332 return true;
5333 }
5334 return false;
5335 }
5336
5337 return HasSubOverflow(cast<ConstantInt>(Result),
5338 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5339 IsSigned);
5340}
5341
Chris Lattner574da9b2005-01-13 20:14:25 +00005342/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5343/// code necessary to compute the offset from the base pointer (without adding
5344/// in the base pointer). Return the result as a signed integer of intptr size.
5345static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005346 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005347 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005348 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005349 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005350
5351 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005352 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005353 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005354
Gabor Greif177dd3f2008-06-12 21:37:33 +00005355 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5356 ++i, ++GTI) {
5357 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005358 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005359 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5360 if (OpC->isZero()) continue;
5361
5362 // Handle a struct index, which adds its field offset to the pointer.
5363 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5364 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5365
Chris Lattner74381062009-08-30 07:44:24 +00005366 Result = IC.Builder->CreateAdd(Result,
5367 ConstantInt::get(IntPtrTy, Size),
5368 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005369 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005370 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005371
Owen Andersoneed707b2009-07-24 23:12:02 +00005372 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005373 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005374 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5375 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005376 // Emit an add instruction.
5377 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005378 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005379 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005380 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005381 if (Op->getType() != IntPtrTy)
5382 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005383 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005384 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005385 // We'll let instcombine(mul) convert this to a shl if possible.
5386 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005387 }
5388
5389 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005390 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005391 }
5392 return Result;
5393}
5394
Chris Lattner10c0d912008-04-22 02:53:33 +00005395
Dan Gohman8f080f02009-07-17 22:16:21 +00005396/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5397/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5398/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5399/// be complex, and scales are involved. The above expression would also be
5400/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5401/// This later form is less amenable to optimization though, and we are allowed
5402/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005403///
5404/// If we can't emit an optimized form for this expression, this returns null.
5405///
5406static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5407 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005408 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005409 gep_type_iterator GTI = gep_type_begin(GEP);
5410
5411 // Check to see if this gep only has a single variable index. If so, and if
5412 // any constant indices are a multiple of its scale, then we can compute this
5413 // in terms of the scale of the variable index. For example, if the GEP
5414 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5415 // because the expression will cross zero at the same point.
5416 unsigned i, e = GEP->getNumOperands();
5417 int64_t Offset = 0;
5418 for (i = 1; i != e; ++i, ++GTI) {
5419 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5420 // Compute the aggregate offset of constant indices.
5421 if (CI->isZero()) continue;
5422
5423 // Handle a struct index, which adds its field offset to the pointer.
5424 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5425 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5426 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005427 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005428 Offset += Size*CI->getSExtValue();
5429 }
5430 } else {
5431 // Found our variable index.
5432 break;
5433 }
5434 }
5435
5436 // If there are no variable indices, we must have a constant offset, just
5437 // evaluate it the general way.
5438 if (i == e) return 0;
5439
5440 Value *VariableIdx = GEP->getOperand(i);
5441 // Determine the scale factor of the variable element. For example, this is
5442 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005443 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005444
5445 // Verify that there are no other variable indices. If so, emit the hard way.
5446 for (++i, ++GTI; i != e; ++i, ++GTI) {
5447 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5448 if (!CI) return 0;
5449
5450 // Compute the aggregate offset of constant indices.
5451 if (CI->isZero()) continue;
5452
5453 // Handle a struct index, which adds its field offset to the pointer.
5454 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5455 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5456 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005457 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005458 Offset += Size*CI->getSExtValue();
5459 }
5460 }
5461
5462 // Okay, we know we have a single variable index, which must be a
5463 // pointer/array/vector index. If there is no offset, life is simple, return
5464 // the index.
5465 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5466 if (Offset == 0) {
5467 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5468 // we don't need to bother extending: the extension won't affect where the
5469 // computation crosses zero.
5470 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005471 VariableIdx = new TruncInst(VariableIdx,
5472 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005473 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005474 return VariableIdx;
5475 }
5476
5477 // Otherwise, there is an index. The computation we will do will be modulo
5478 // the pointer size, so get it.
5479 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5480
5481 Offset &= PtrSizeMask;
5482 VariableScale &= PtrSizeMask;
5483
5484 // To do this transformation, any constant index must be a multiple of the
5485 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5486 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5487 // multiple of the variable scale.
5488 int64_t NewOffs = Offset / (int64_t)VariableScale;
5489 if (Offset != NewOffs*(int64_t)VariableScale)
5490 return 0;
5491
5492 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005493 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005494 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005495 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005496 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005497 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005498 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005499 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005500}
5501
5502
Reid Spencere4d87aa2006-12-23 06:05:41 +00005503/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005504/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005505Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005506 ICmpInst::Predicate Cond,
5507 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005508 // Look through bitcasts.
5509 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5510 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005511
Chris Lattner574da9b2005-01-13 20:14:25 +00005512 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005513 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005514 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005515 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005516 // know pointers can't overflow since the gep is inbounds. See if we can
5517 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005518 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5519
5520 // If not, synthesize the offset the hard way.
5521 if (Offset == 0)
5522 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005523 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005524 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005525 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005526 // If the base pointers are different, but the indices are the same, just
5527 // compare the base pointer.
5528 if (PtrBase != GEPRHS->getOperand(0)) {
5529 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005530 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005531 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005532 if (IndicesTheSame)
5533 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5534 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5535 IndicesTheSame = false;
5536 break;
5537 }
5538
5539 // If all indices are the same, just compare the base pointers.
5540 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005541 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005542 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005543
5544 // Otherwise, the base pointers are different and the indices are
5545 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005546 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005547 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005548
Chris Lattnere9d782b2005-01-13 22:25:21 +00005549 // If one of the GEPs has all zero indices, recurse.
5550 bool AllZeros = true;
5551 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5552 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5553 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5554 AllZeros = false;
5555 break;
5556 }
5557 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005558 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5559 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005560
5561 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005562 AllZeros = true;
5563 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5564 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5565 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5566 AllZeros = false;
5567 break;
5568 }
5569 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005570 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005571
Chris Lattner4401c9c2005-01-14 00:20:05 +00005572 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5573 // If the GEPs only differ by one index, compare it.
5574 unsigned NumDifferences = 0; // Keep track of # differences.
5575 unsigned DiffOperand = 0; // The operand that differs.
5576 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5577 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005578 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5579 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005580 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005581 NumDifferences = 2;
5582 break;
5583 } else {
5584 if (NumDifferences++) break;
5585 DiffOperand = i;
5586 }
5587 }
5588
5589 if (NumDifferences == 0) // SAME GEP?
5590 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005591 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005592 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005593
Chris Lattner4401c9c2005-01-14 00:20:05 +00005594 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005595 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5596 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005597 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005598 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005599 }
5600 }
5601
Reid Spencere4d87aa2006-12-23 06:05:41 +00005602 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005603 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005604 if (TD &&
5605 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005606 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5607 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5608 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5609 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005610 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005611 }
5612 }
5613 return 0;
5614}
5615
Chris Lattnera5406232008-05-19 20:18:56 +00005616/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5617///
5618Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5619 Instruction *LHSI,
5620 Constant *RHSC) {
5621 if (!isa<ConstantFP>(RHSC)) return 0;
5622 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5623
5624 // Get the width of the mantissa. We don't want to hack on conversions that
5625 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005626 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005627 if (MantissaWidth == -1) return 0; // Unknown.
5628
5629 // Check to see that the input is converted from an integer type that is small
5630 // enough that preserves all bits. TODO: check here for "known" sign bits.
5631 // 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 +00005632 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005633
5634 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005635 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5636 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005637 ++InputSize;
5638
5639 // If the conversion would lose info, don't hack on this.
5640 if ((int)InputSize > MantissaWidth)
5641 return 0;
5642
5643 // Otherwise, we can potentially simplify the comparison. We know that it
5644 // will always come through as an integer value and we know the constant is
5645 // not a NAN (it would have been previously simplified).
5646 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5647
5648 ICmpInst::Predicate Pred;
5649 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005650 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005651 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005652 case FCmpInst::FCMP_OEQ:
5653 Pred = ICmpInst::ICMP_EQ;
5654 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005655 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005656 case FCmpInst::FCMP_OGT:
5657 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5658 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005659 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005660 case FCmpInst::FCMP_OGE:
5661 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5662 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005663 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005664 case FCmpInst::FCMP_OLT:
5665 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5666 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005667 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005668 case FCmpInst::FCMP_OLE:
5669 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5670 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005671 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005672 case FCmpInst::FCMP_ONE:
5673 Pred = ICmpInst::ICMP_NE;
5674 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005675 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005676 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005677 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005678 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005679 }
5680
5681 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5682
5683 // Now we know that the APFloat is a normal number, zero or inf.
5684
Chris Lattner85162782008-05-20 03:50:52 +00005685 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005686 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005687 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005688
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005689 if (!LHSUnsigned) {
5690 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5691 // and large values.
5692 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5693 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5694 APFloat::rmNearestTiesToEven);
5695 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5696 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5697 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005698 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5699 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005700 }
5701 } else {
5702 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5703 // +INF and large values.
5704 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5705 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5706 APFloat::rmNearestTiesToEven);
5707 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5708 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5709 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005710 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5711 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005712 }
Chris Lattnera5406232008-05-19 20:18:56 +00005713 }
5714
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005715 if (!LHSUnsigned) {
5716 // See if the RHS value is < SignedMin.
5717 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5718 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5719 APFloat::rmNearestTiesToEven);
5720 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5721 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5722 Pred == ICmpInst::ICMP_SGE)
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 }
Chris Lattnera5406232008-05-19 20:18:56 +00005726 }
5727
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005728 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5729 // [0, UMAX], but it may still be fractional. See if it is fractional by
5730 // casting the FP value to the integer value and back, checking for equality.
5731 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005732 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005733 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5734 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005735 if (!RHS.isZero()) {
5736 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005737 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5738 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005739 if (!Equal) {
5740 // If we had a comparison against a fractional value, we have to adjust
5741 // the compare predicate and sometimes the value. RHSC is rounded towards
5742 // zero at this point.
5743 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005744 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005745 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005746 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005747 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005748 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005749 case ICmpInst::ICMP_ULE:
5750 // (float)int <= 4.4 --> int <= 4
5751 // (float)int <= -4.4 --> false
5752 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005753 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005754 break;
5755 case ICmpInst::ICMP_SLE:
5756 // (float)int <= 4.4 --> int <= 4
5757 // (float)int <= -4.4 --> int < -4
5758 if (RHS.isNegative())
5759 Pred = ICmpInst::ICMP_SLT;
5760 break;
5761 case ICmpInst::ICMP_ULT:
5762 // (float)int < -4.4 --> false
5763 // (float)int < 4.4 --> int <= 4
5764 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005765 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005766 Pred = ICmpInst::ICMP_ULE;
5767 break;
5768 case ICmpInst::ICMP_SLT:
5769 // (float)int < -4.4 --> int < -4
5770 // (float)int < 4.4 --> int <= 4
5771 if (!RHS.isNegative())
5772 Pred = ICmpInst::ICMP_SLE;
5773 break;
5774 case ICmpInst::ICMP_UGT:
5775 // (float)int > 4.4 --> int > 4
5776 // (float)int > -4.4 --> true
5777 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005778 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005779 break;
5780 case ICmpInst::ICMP_SGT:
5781 // (float)int > 4.4 --> int > 4
5782 // (float)int > -4.4 --> int >= -4
5783 if (RHS.isNegative())
5784 Pred = ICmpInst::ICMP_SGE;
5785 break;
5786 case ICmpInst::ICMP_UGE:
5787 // (float)int >= -4.4 --> true
5788 // (float)int >= 4.4 --> int > 4
5789 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005790 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005791 Pred = ICmpInst::ICMP_UGT;
5792 break;
5793 case ICmpInst::ICMP_SGE:
5794 // (float)int >= -4.4 --> int >= -4
5795 // (float)int >= 4.4 --> int > 4
5796 if (!RHS.isNegative())
5797 Pred = ICmpInst::ICMP_SGT;
5798 break;
5799 }
Chris Lattnera5406232008-05-19 20:18:56 +00005800 }
5801 }
5802
5803 // Lower this FP comparison into an appropriate integer version of the
5804 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005805 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005806}
5807
Reid Spencere4d87aa2006-12-23 06:05:41 +00005808Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5809 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005810 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005811
Chris Lattner58e97462007-01-14 19:42:17 +00005812 // Fold trivial predicates.
5813 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005814 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005815 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005816 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005817
5818 // Simplify 'fcmp pred X, X'
5819 if (Op0 == Op1) {
5820 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005821 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005822 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5823 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5824 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005825 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005826 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5827 case FCmpInst::FCMP_OLT: // True if ordered and less than
5828 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005829 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005830
5831 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5832 case FCmpInst::FCMP_ULT: // True if unordered or less than
5833 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5834 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5835 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5836 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005837 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005838 return &I;
5839
5840 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5841 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5842 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5843 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5844 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5845 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005846 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005847 return &I;
5848 }
5849 }
5850
Reid Spencere4d87aa2006-12-23 06:05:41 +00005851 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005852 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005853
Reid Spencere4d87aa2006-12-23 06:05:41 +00005854 // Handle fcmp with constant RHS
5855 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005856 // If the constant is a nan, see if we can fold the comparison based on it.
5857 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5858 if (CFP->getValueAPF().isNaN()) {
5859 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005860 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005861 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5862 "Comparison must be either ordered or unordered!");
5863 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005864 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005865 }
5866 }
5867
Reid Spencere4d87aa2006-12-23 06:05:41 +00005868 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5869 switch (LHSI->getOpcode()) {
5870 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005871 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5872 // block. If in the same block, we're encouraging jump threading. If
5873 // not, we are just pessimizing the code by making an i1 phi.
5874 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005875 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005876 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005877 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005878 case Instruction::SIToFP:
5879 case Instruction::UIToFP:
5880 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5881 return NV;
5882 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005883 case Instruction::Select:
5884 // If either operand of the select is a constant, we can fold the
5885 // comparison into the select arms, which will cause one to be
5886 // constant folded and the select turned into a bitwise or.
5887 Value *Op1 = 0, *Op2 = 0;
5888 if (LHSI->hasOneUse()) {
5889 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5890 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005891 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005893 Op2 = Builder->CreateFCmp(I.getPredicate(),
5894 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005895 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5896 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005897 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005898 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005899 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5900 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005901 }
5902 }
5903
5904 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005905 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005906 break;
5907 }
5908 }
5909
5910 return Changed ? &I : 0;
5911}
5912
5913Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5914 bool Changed = SimplifyCompare(I);
5915 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5916 const Type *Ty = Op0->getType();
5917
5918 // icmp X, X
5919 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005920 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005921 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922
5923 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005924 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005925
Reid Spencere4d87aa2006-12-23 06:05:41 +00005926 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005927 // addresses never equal each other! We already know that Op0 != Op1.
Chris Lattnerbbc33852009-10-05 02:47:47 +00005928 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005929 isa<ConstantPointerNull>(Op0)) &&
Chris Lattnerbbc33852009-10-05 02:47:47 +00005930 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005931 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005932 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005933 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005934
Reid Spencere4d87aa2006-12-23 06:05:41 +00005935 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005936 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005938 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005939 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005940 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005941 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005942 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005943 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005944 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005945
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005947 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005948 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005949 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005950 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005951 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005952 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005953 case ICmpInst::ICMP_SGT:
5954 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005955 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005956 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005957 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005958 return BinaryOperator::CreateAnd(Not, Op0);
5959 }
5960 case ICmpInst::ICMP_UGE:
5961 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5962 // FALL THROUGH
5963 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005964 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005965 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005966 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005967 case ICmpInst::ICMP_SGE:
5968 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5969 // FALL THROUGH
5970 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005971 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005972 return BinaryOperator::CreateOr(Not, Op0);
5973 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005974 }
Chris Lattner8b170942002-08-09 23:47:40 +00005975 }
5976
Dan Gohman1c8491e2009-04-25 17:12:48 +00005977 unsigned BitWidth = 0;
5978 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005979 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5980 else if (Ty->isIntOrIntVector())
5981 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005982
5983 bool isSignBit = false;
5984
Dan Gohman81b28ce2008-09-16 18:46:06 +00005985 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005986 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005987 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005988
Chris Lattnerb6566012008-01-05 01:18:20 +00005989 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5990 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005991 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005992 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005993 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005994 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005995
Dan Gohman81b28ce2008-09-16 18:46:06 +00005996 // If we have an icmp le or icmp ge instruction, turn it into the
5997 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5998 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005999 switch (I.getPredicate()) {
6000 default: break;
6001 case ICmpInst::ICMP_ULE:
6002 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006003 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006004 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006005 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006006 case ICmpInst::ICMP_SLE:
6007 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006008 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006009 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006010 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006011 case ICmpInst::ICMP_UGE:
6012 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006013 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006014 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006015 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006016 case ICmpInst::ICMP_SGE:
6017 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006018 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006019 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006020 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006021 }
6022
Chris Lattner183661e2008-07-11 05:40:05 +00006023 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006024 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006025 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006026 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6027 }
6028
6029 // See if we can fold the comparison based on range information we can get
6030 // by checking whether bits are known to be zero or one in the input.
6031 if (BitWidth != 0) {
6032 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6033 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6034
6035 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006036 isSignBit ? APInt::getSignBit(BitWidth)
6037 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006038 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006039 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006040 if (SimplifyDemandedBits(I.getOperandUse(1),
6041 APInt::getAllOnesValue(BitWidth),
6042 Op1KnownZero, Op1KnownOne, 0))
6043 return &I;
6044
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006045 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006046 // in. Compute the Min, Max and RHS values based on the known bits. For the
6047 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006048 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6049 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6050 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6051 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6052 Op0Min, Op0Max);
6053 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6054 Op1Min, Op1Max);
6055 } else {
6056 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6057 Op0Min, Op0Max);
6058 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6059 Op1Min, Op1Max);
6060 }
6061
Chris Lattner183661e2008-07-11 05:40:05 +00006062 // If Min and Max are known to be the same, then SimplifyDemandedBits
6063 // figured out that the LHS is a constant. Just constant fold this now so
6064 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006065 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006066 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006067 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006068 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006069 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006070 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006071
Chris Lattner183661e2008-07-11 05:40:05 +00006072 // Based on the range information we know about the LHS, see if we can
6073 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006075 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006076 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006077 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006078 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006079 break;
6080 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006081 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006082 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006083 break;
6084 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006085 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006086 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006087 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006088 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006089 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006090 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006091 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6092 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006093 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006094 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006095
6096 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6097 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006098 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006099 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100 }
Chris Lattner84dff672008-07-11 05:08:55 +00006101 break;
6102 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006104 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006106 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107
6108 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006109 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6111 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006112 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006113 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114
6115 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6116 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006117 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006118 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 }
Chris Lattner84dff672008-07-11 05:08:55 +00006120 break;
6121 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006122 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006123 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006124 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006125 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006127 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6129 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006130 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006131 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 }
Chris Lattner84dff672008-07-11 05:08:55 +00006133 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006134 case ICmpInst::ICMP_SGT:
6135 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006136 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006138 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139
6140 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006141 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6143 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006144 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006145 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 }
6147 break;
6148 case ICmpInst::ICMP_SGE:
6149 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6150 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006151 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006153 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 break;
6155 case ICmpInst::ICMP_SLE:
6156 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6157 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006158 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 break;
6162 case ICmpInst::ICMP_UGE:
6163 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6164 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006165 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006167 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 break;
6169 case ICmpInst::ICMP_ULE:
6170 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6171 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006172 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006174 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006175 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006176 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177
6178 // Turn a signed comparison into an unsigned one if both operands
6179 // are known to have the same sign.
6180 if (I.isSignedPredicate() &&
6181 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6182 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006183 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006184 }
6185
6186 // Test if the ICmpInst instruction is used exclusively by a select as
6187 // part of a minimum or maximum operation. If so, refrain from doing
6188 // any other folding. This helps out other analyses which understand
6189 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6190 // and CodeGen. And in this case, at least one of the comparison
6191 // operands has at least one user besides the compare (the select),
6192 // which would often largely negate the benefit of folding anyway.
6193 if (I.hasOneUse())
6194 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6195 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6196 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6197 return 0;
6198
6199 // See if we are doing a comparison between a constant and an instruction that
6200 // can be folded into the comparison.
6201 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006202 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006203 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006204 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006205 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006206 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6207 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006208 }
6209
Chris Lattner01deb9d2007-04-03 17:43:25 +00006210 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006211 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6212 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6213 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006214 case Instruction::GetElementPtr:
6215 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006216 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006217 bool isAllZeros = true;
6218 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6219 if (!isa<Constant>(LHSI->getOperand(i)) ||
6220 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6221 isAllZeros = false;
6222 break;
6223 }
6224 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006225 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006226 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006227 }
6228 break;
6229
Chris Lattner6970b662005-04-23 15:31:55 +00006230 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006231 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006232 // block. If in the same block, we're encouraging jump threading. If
6233 // not, we are just pessimizing the code by making an i1 phi.
6234 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006235 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006236 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006237 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006238 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006239 // If either operand of the select is a constant, we can fold the
6240 // comparison into the select arms, which will cause one to be
6241 // constant folded and the select turned into a bitwise or.
6242 Value *Op1 = 0, *Op2 = 0;
6243 if (LHSI->hasOneUse()) {
6244 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6245 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006246 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006247 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006248 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6249 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006250 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6251 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006252 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006253 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006254 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6255 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006256 }
6257 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006258
Chris Lattner6970b662005-04-23 15:31:55 +00006259 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006260 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006261 break;
6262 }
Chris Lattner4802d902007-04-06 18:57:34 +00006263 case Instruction::Malloc:
6264 // If we have (malloc != null), and if the malloc has a single use, we
6265 // can assume it is successful and remove the malloc.
6266 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006267 Worklist.Add(LHSI);
Victor Hernandez83d63912009-09-18 22:35:49 +00006268 return ReplaceInstUsesWith(I,
6269 ConstantInt::get(Type::getInt1Ty(*Context),
6270 !I.isTrueWhenEqual()));
6271 }
6272 break;
6273 case Instruction::Call:
6274 // If we have (malloc != null), and if the malloc has a single use, we
6275 // can assume it is successful and remove the malloc.
6276 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6277 isa<ConstantPointerNull>(RHSC)) {
6278 Worklist.Add(LHSI);
6279 return ReplaceInstUsesWith(I,
6280 ConstantInt::get(Type::getInt1Ty(*Context),
6281 !I.isTrueWhenEqual()));
6282 }
6283 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006284 }
Chris Lattner6970b662005-04-23 15:31:55 +00006285 }
6286
Reid Spencere4d87aa2006-12-23 06:05:41 +00006287 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006288 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006289 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006290 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006291 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6293 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006294 return NI;
6295
Reid Spencere4d87aa2006-12-23 06:05:41 +00006296 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006297 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6298 // now.
6299 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6300 if (isa<PointerType>(Op0->getType()) &&
6301 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006302 // We keep moving the cast from the left operand over to the right
6303 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006304 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006305
Chris Lattner57d86372007-01-06 01:45:59 +00006306 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6307 // so eliminate it as well.
6308 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6309 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006310
Chris Lattnerde90b762003-11-03 04:25:02 +00006311 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006312 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006313 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006314 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006315 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006316 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006317 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006318 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006319 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006320 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006321 }
Chris Lattner57d86372007-01-06 01:45:59 +00006322 }
6323
6324 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006326 // This comes up when you have code like
6327 // int X = A < B;
6328 // if (X) ...
6329 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006330 // with a constant or another cast from the same type.
6331 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006332 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006333 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006334 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006335
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006336 // See if it's the same type of instruction on the left and right.
6337 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6338 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006339 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006340 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006341 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006342 default: break;
6343 case Instruction::Add:
6344 case Instruction::Sub:
6345 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006346 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006347 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006348 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006349 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6350 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6351 if (CI->getValue().isSignBit()) {
6352 ICmpInst::Predicate Pred = I.isSignedPredicate()
6353 ? I.getUnsignedPredicate()
6354 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006355 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006356 Op1I->getOperand(0));
6357 }
6358
6359 if (CI->getValue().isMaxSignedValue()) {
6360 ICmpInst::Predicate Pred = I.isSignedPredicate()
6361 ? I.getUnsignedPredicate()
6362 : I.getSignedPredicate();
6363 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006364 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006365 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006366 }
6367 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006368 break;
6369 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006370 if (!I.isEquality())
6371 break;
6372
Nick Lewycky5d52c452008-08-21 05:56:10 +00006373 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6374 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6375 // Mask = -1 >> count-trailing-zeros(Cst).
6376 if (!CI->isZero() && !CI->isOne()) {
6377 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006378 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006379 APInt::getLowBitsSet(AP.getBitWidth(),
6380 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006381 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006382 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6383 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006384 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006385 }
6386 }
6387 break;
6388 }
6389 }
6390 }
6391 }
6392
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006393 // ~x < ~y --> y < x
6394 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006395 if (match(Op0, m_Not(m_Value(A))) &&
6396 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006397 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006398 }
6399
Chris Lattner65b72ba2006-09-18 04:22:48 +00006400 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006401 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006402
6403 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006404 if (match(Op0, m_Neg(m_Value(A))) &&
6405 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006406 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006407
Dan Gohman4ae51262009-08-12 16:23:25 +00006408 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006409 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6410 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006411 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006412 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006413 }
6414
Dan Gohman4ae51262009-08-12 16:23:25 +00006415 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006416 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006417 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006418 if (match(B, m_ConstantInt(C1)) &&
6419 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006420 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006421 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006422 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6423 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006424 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006425
6426 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006427 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6428 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6429 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6430 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006431 }
6432 }
6433
Dan Gohman4ae51262009-08-12 16:23:25 +00006434 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006435 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006436 // A == (A^B) -> B == 0
6437 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006438 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006439 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006440 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006441
6442 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006443 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006444 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006445 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006446
6447 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006448 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006449 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006450 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006451
Chris Lattner9c2328e2006-11-14 06:06:06 +00006452 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6453 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006454 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6455 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006456 Value *X = 0, *Y = 0, *Z = 0;
6457
6458 if (A == C) {
6459 X = B; Y = D; Z = A;
6460 } else if (A == D) {
6461 X = B; Y = C; Z = A;
6462 } else if (B == C) {
6463 X = A; Y = D; Z = B;
6464 } else if (B == D) {
6465 X = A; Y = C; Z = B;
6466 }
6467
6468 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006469 Op1 = Builder->CreateXor(X, Y, "tmp");
6470 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006471 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006472 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006473 return &I;
6474 }
6475 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006476 }
Chris Lattner7e708292002-06-25 16:13:24 +00006477 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006478}
6479
Chris Lattner562ef782007-06-20 23:46:26 +00006480
6481/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6482/// and CmpRHS are both known to be integer constants.
6483Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6484 ConstantInt *DivRHS) {
6485 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6486 const APInt &CmpRHSV = CmpRHS->getValue();
6487
6488 // FIXME: If the operand types don't match the type of the divide
6489 // then don't attempt this transform. The code below doesn't have the
6490 // logic to deal with a signed divide and an unsigned compare (and
6491 // vice versa). This is because (x /s C1) <s C2 produces different
6492 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6493 // (x /u C1) <u C2. Simply casting the operands and result won't
6494 // work. :( The if statement below tests that condition and bails
6495 // if it finds it.
6496 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6497 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6498 return 0;
6499 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006500 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006501 if (DivIsSigned && DivRHS->isAllOnesValue())
6502 return 0; // The overflow computation also screws up here
6503 if (DivRHS->isOne())
6504 return 0; // Not worth bothering, and eliminates some funny cases
6505 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006506
6507 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6508 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6509 // C2 (CI). By solving for X we can turn this into a range check
6510 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006511 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006512
6513 // Determine if the product overflows by seeing if the product is
6514 // not equal to the divide. Make sure we do the same kind of divide
6515 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006516 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6517 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006518
6519 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006520 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006521
Chris Lattner1dbfd482007-06-21 18:11:19 +00006522 // Figure out the interval that is being checked. For example, a comparison
6523 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6524 // Compute this interval based on the constants involved and the signedness of
6525 // the compare/divide. This computes a half-open interval, keeping track of
6526 // whether either value in the interval overflows. After analysis each
6527 // overflow variable is set to 0 if it's corresponding bound variable is valid
6528 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6529 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006530 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006531
Chris Lattner562ef782007-06-20 23:46:26 +00006532 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006533 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006534 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006535 HiOverflow = LoOverflow = ProdOV;
6536 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006537 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006538 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006539 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006540 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006541 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006542 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006543 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006544 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6545 HiOverflow = LoOverflow = ProdOV;
6546 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006547 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006548 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006549 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006550 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006551 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6552 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006553 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006554 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006555 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006556 true) ? -1 : 0;
6557 }
Chris Lattner562ef782007-06-20 23:46:26 +00006558 }
Dan Gohman76491272008-02-13 22:09:18 +00006559 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006560 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006561 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006562 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006563 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006564 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6565 HiOverflow = 1; // [INTMIN+1, overflow)
6566 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6567 }
Dan Gohman76491272008-02-13 22:09:18 +00006568 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006569 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006570 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006571 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006572 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006573 LoOverflow = AddWithOverflow(LoBound, HiBound,
6574 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006575 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006576 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6577 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006578 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006579 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006580 }
6581
Chris Lattner1dbfd482007-06-21 18:11:19 +00006582 // Dividing by a negative swaps the condition. LT <-> GT
6583 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006584 }
6585
6586 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006587 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006588 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006589 case ICmpInst::ICMP_EQ:
6590 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006591 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006592 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006593 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006594 ICmpInst::ICMP_UGE, X, LoBound);
6595 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006596 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006597 ICmpInst::ICMP_ULT, X, HiBound);
6598 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006599 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006600 case ICmpInst::ICMP_NE:
6601 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006602 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006603 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006604 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006605 ICmpInst::ICMP_ULT, X, LoBound);
6606 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006607 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006608 ICmpInst::ICMP_UGE, X, HiBound);
6609 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006610 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006611 case ICmpInst::ICMP_ULT:
6612 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006613 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006614 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006615 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006616 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006617 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006618 case ICmpInst::ICMP_UGT:
6619 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006620 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006621 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006623 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006625 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006626 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006627 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006628 }
6629}
6630
6631
Chris Lattner01deb9d2007-04-03 17:43:25 +00006632/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6633///
6634Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6635 Instruction *LHSI,
6636 ConstantInt *RHS) {
6637 const APInt &RHSV = RHS->getValue();
6638
6639 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006640 case Instruction::Trunc:
6641 if (ICI.isEquality() && LHSI->hasOneUse()) {
6642 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6643 // of the high bits truncated out of x are known.
6644 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6645 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6646 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6647 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6648 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6649
6650 // If all the high bits are known, we can do this xform.
6651 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6652 // Pull in the high bits from known-ones set.
6653 APInt NewRHS(RHS->getValue());
6654 NewRHS.zext(SrcBits);
6655 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006656 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006657 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006658 }
6659 }
6660 break;
6661
Duncan Sands0091bf22007-04-04 06:42:45 +00006662 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006663 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6664 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6665 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006666 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6667 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006668 Value *CompareVal = LHSI->getOperand(0);
6669
6670 // If the sign bit of the XorCST is not set, there is no change to
6671 // the operation, just stop using the Xor.
6672 if (!XorCST->getValue().isNegative()) {
6673 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006674 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006675 return &ICI;
6676 }
6677
6678 // Was the old condition true if the operand is positive?
6679 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6680
6681 // If so, the new one isn't.
6682 isTrueIfPositive ^= true;
6683
6684 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006685 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006686 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006687 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006688 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006689 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006690 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006691
6692 if (LHSI->hasOneUse()) {
6693 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6694 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6695 const APInt &SignBit = XorCST->getValue();
6696 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6697 ? ICI.getUnsignedPredicate()
6698 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006699 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006700 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006701 }
6702
6703 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006704 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006705 const APInt &NotSignBit = XorCST->getValue();
6706 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6707 ? ICI.getUnsignedPredicate()
6708 : ICI.getSignedPredicate();
6709 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006710 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006711 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006712 }
6713 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006714 }
6715 break;
6716 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6717 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6718 LHSI->getOperand(0)->hasOneUse()) {
6719 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6720
6721 // If the LHS is an AND of a truncating cast, we can widen the
6722 // and/compare to be the input width without changing the value
6723 // produced, eliminating a cast.
6724 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6725 // We can do this transformation if either the AND constant does not
6726 // have its sign bit set or if it is an equality comparison.
6727 // Extending a relational comparison when we're checking the sign
6728 // bit would not work.
6729 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006730 (ICI.isEquality() ||
6731 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006732 uint32_t BitWidth =
6733 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6734 APInt NewCST = AndCST->getValue();
6735 NewCST.zext(BitWidth);
6736 APInt NewCI = RHSV;
6737 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006738 Value *NewAnd =
6739 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006740 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006741 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006742 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006743 }
6744 }
6745
6746 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6747 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6748 // happens a LOT in code produced by the C front-end, for bitfield
6749 // access.
6750 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6751 if (Shift && !Shift->isShift())
6752 Shift = 0;
6753
6754 ConstantInt *ShAmt;
6755 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6756 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6757 const Type *AndTy = AndCST->getType(); // Type of the and.
6758
6759 // We can fold this as long as we can't shift unknown bits
6760 // into the mask. This can only happen with signed shift
6761 // rights, as they sign-extend.
6762 if (ShAmt) {
6763 bool CanFold = Shift->isLogicalShift();
6764 if (!CanFold) {
6765 // To test for the bad case of the signed shr, see if any
6766 // of the bits shifted in could be tested after the mask.
6767 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6768 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6769
6770 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6771 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6772 AndCST->getValue()) == 0)
6773 CanFold = true;
6774 }
6775
6776 if (CanFold) {
6777 Constant *NewCst;
6778 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006779 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006780 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006781 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782
6783 // Check to see if we are shifting out any of the bits being
6784 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006785 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006786 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006787 // If we shifted bits out, the fold is not going to work out.
6788 // As a special case, check to see if this means that the
6789 // result is always true or false now.
6790 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006791 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006792 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006793 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006794 } else {
6795 ICI.setOperand(1, NewCst);
6796 Constant *NewAndCST;
6797 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006798 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006799 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006800 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006801 LHSI->setOperand(1, NewAndCST);
6802 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006803 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006804 return &ICI;
6805 }
6806 }
6807 }
6808
6809 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6810 // preferable because it allows the C<<Y expression to be hoisted out
6811 // of a loop if Y is invariant and X is not.
6812 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006813 ICI.isEquality() && !Shift->isArithmeticShift() &&
6814 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006815 // Compute C << Y.
6816 Value *NS;
6817 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006818 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006819 } else {
6820 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006821 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006822 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006823
6824 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006825 Value *NewAnd =
6826 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006827
6828 ICI.setOperand(0, NewAnd);
6829 return &ICI;
6830 }
6831 }
6832 break;
6833
Chris Lattnera0141b92007-07-15 20:42:37 +00006834 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6835 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6836 if (!ShAmt) break;
6837
6838 uint32_t TypeBits = RHSV.getBitWidth();
6839
6840 // Check that the shift amount is in range. If not, don't perform
6841 // undefined shifts. When the shift is visited it will be
6842 // simplified.
6843 if (ShAmt->uge(TypeBits))
6844 break;
6845
6846 if (ICI.isEquality()) {
6847 // If we are comparing against bits always shifted out, the
6848 // comparison cannot succeed.
6849 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006850 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006851 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006852 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6853 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006854 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006855 return ReplaceInstUsesWith(ICI, Cst);
6856 }
6857
6858 if (LHSI->hasOneUse()) {
6859 // Otherwise strength reduce the shift into an and.
6860 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6861 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006862 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006863 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006864
Chris Lattner74381062009-08-30 07:44:24 +00006865 Value *And =
6866 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006867 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006868 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006869 }
6870 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006871
6872 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6873 bool TrueIfSigned = false;
6874 if (LHSI->hasOneUse() &&
6875 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6876 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006877 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006878 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006879 Value *And =
6880 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006881 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006882 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006883 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006885 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006886
6887 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006888 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006889 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006890 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006891 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006892
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006893 // Check that the shift amount is in range. If not, don't perform
6894 // undefined shifts. When the shift is visited it will be
6895 // simplified.
6896 uint32_t TypeBits = RHSV.getBitWidth();
6897 if (ShAmt->uge(TypeBits))
6898 break;
6899
6900 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006901
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006902 // If we are comparing against bits always shifted out, the
6903 // comparison cannot succeed.
6904 APInt Comp = RHSV << ShAmtVal;
6905 if (LHSI->getOpcode() == Instruction::LShr)
6906 Comp = Comp.lshr(ShAmtVal);
6907 else
6908 Comp = Comp.ashr(ShAmtVal);
6909
6910 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6911 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006912 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006913 return ReplaceInstUsesWith(ICI, Cst);
6914 }
6915
6916 // Otherwise, check to see if the bits shifted out are known to be zero.
6917 // If so, we can compare against the unshifted value:
6918 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006919 if (LHSI->hasOneUse() &&
6920 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006921 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006922 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006923 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006924 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006925
Evan Chengf30752c2008-04-23 00:38:06 +00006926 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006927 // Otherwise strength reduce the shift into an and.
6928 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006929 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006930
Chris Lattner74381062009-08-30 07:44:24 +00006931 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6932 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006933 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006934 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006935 }
6936 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006937 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006938
6939 case Instruction::SDiv:
6940 case Instruction::UDiv:
6941 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6942 // Fold this div into the comparison, producing a range check.
6943 // Determine, based on the divide type, what the range is being
6944 // checked. If there is an overflow on the low or high side, remember
6945 // it, otherwise compute the range [low, hi) bounding the new value.
6946 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006947 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6948 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6949 DivRHS))
6950 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006951 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006952
6953 case Instruction::Add:
6954 // Fold: icmp pred (add, X, C1), C2
6955
6956 if (!ICI.isEquality()) {
6957 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6958 if (!LHSC) break;
6959 const APInt &LHSV = LHSC->getValue();
6960
6961 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6962 .subtract(LHSV);
6963
6964 if (ICI.isSignedPredicate()) {
6965 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006966 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006967 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006968 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006969 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006970 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006971 }
6972 } else {
6973 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006974 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006975 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006976 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006977 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006978 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006979 }
6980 }
6981 }
6982 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006983 }
6984
6985 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6986 if (ICI.isEquality()) {
6987 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6988
6989 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6990 // the second operand is a constant, simplify a bit.
6991 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6992 switch (BO->getOpcode()) {
6993 case Instruction::SRem:
6994 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6995 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6996 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6997 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006998 Value *NewRem =
6999 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7000 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007001 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007002 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007003 }
7004 }
7005 break;
7006 case Instruction::Add:
7007 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7008 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7009 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007010 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007011 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007012 } else if (RHSV == 0) {
7013 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7014 // efficiently invertible, or if the add has just this one use.
7015 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7016
Dan Gohman186a6362009-08-12 16:04:34 +00007017 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007018 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007019 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007020 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007021 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007022 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007023 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007024 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007025 }
7026 }
7027 break;
7028 case Instruction::Xor:
7029 // For the xor case, we can xor two constants together, eliminating
7030 // the explicit xor.
7031 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007032 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007033 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007034
7035 // FALLTHROUGH
7036 case Instruction::Sub:
7037 // Replace (([sub|xor] A, B) != 0) with (A != B)
7038 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007039 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007040 BO->getOperand(1));
7041 break;
7042
7043 case Instruction::Or:
7044 // If bits are being or'd in that are not present in the constant we
7045 // are comparing against, then the comparison could never succeed!
7046 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007047 Constant *NotCI = ConstantExpr::getNot(RHS);
7048 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007049 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007050 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007051 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007052 }
7053 break;
7054
7055 case Instruction::And:
7056 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7057 // If bits are being compared against that are and'd out, then the
7058 // comparison can never succeed!
7059 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007060 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007061 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007062 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007063
7064 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7065 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007066 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007068 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007069
7070 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007071 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007072 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007073 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007074 ICmpInst::Predicate pred = isICMP_NE ?
7075 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007076 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 }
7078
7079 // ((X & ~7) == 0) --> X < 8
7080 if (RHSV == 0 && isHighOnes(BOC)) {
7081 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007082 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007083 ICmpInst::Predicate pred = isICMP_NE ?
7084 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007085 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007086 }
7087 }
7088 default: break;
7089 }
7090 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7091 // Handle icmp {eq|ne} <intrinsic>, intcst.
7092 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007093 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007094 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007095 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007096 return &ICI;
7097 }
7098 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007099 }
7100 return 0;
7101}
7102
7103/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7104/// We only handle extending casts so far.
7105///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007106Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7107 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007108 Value *LHSCIOp = LHSCI->getOperand(0);
7109 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007110 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007111 Value *RHSCIOp;
7112
Chris Lattner8c756c12007-05-05 22:41:33 +00007113 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7114 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007115 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7116 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007117 cast<IntegerType>(DestTy)->getBitWidth()) {
7118 Value *RHSOp = 0;
7119 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007120 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007121 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7122 RHSOp = RHSC->getOperand(0);
7123 // If the pointer types don't match, insert a bitcast.
7124 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007125 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007126 }
7127
7128 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007129 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007130 }
7131
7132 // The code below only handles extension cast instructions, so far.
7133 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007134 if (LHSCI->getOpcode() != Instruction::ZExt &&
7135 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007136 return 0;
7137
Reid Spencere4d87aa2006-12-23 06:05:41 +00007138 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7139 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007140
Reid Spencere4d87aa2006-12-23 06:05:41 +00007141 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007142 // Not an extension from the same type?
7143 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007144 if (RHSCIOp->getType() != LHSCIOp->getType())
7145 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007146
Nick Lewycky4189a532008-01-28 03:48:02 +00007147 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007148 // and the other is a zext), then we can't handle this.
7149 if (CI->getOpcode() != LHSCI->getOpcode())
7150 return 0;
7151
Nick Lewycky4189a532008-01-28 03:48:02 +00007152 // Deal with equality cases early.
7153 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007154 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007155
7156 // A signed comparison of sign extended values simplifies into a
7157 // signed comparison.
7158 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007159 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007160
7161 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007162 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007163 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007164
Reid Spencere4d87aa2006-12-23 06:05:41 +00007165 // If we aren't dealing with a constant on the RHS, exit early
7166 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7167 if (!CI)
7168 return 0;
7169
7170 // Compute the constant that would happen if we truncated to SrcTy then
7171 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007172 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7173 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007174 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007175
7176 // If the re-extended constant didn't change...
7177 if (Res2 == CI) {
7178 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7179 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007180 // %A = sext i16 %X to i32
7181 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007182 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007183 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007184 // because %A may have negative value.
7185 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007186 // However, we allow this when the compare is EQ/NE, because they are
7187 // signless.
7188 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007189 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007190 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191 }
7192
7193 // The re-extended constant changed so the constant cannot be represented
7194 // in the shorter type. Consequently, we cannot emit a simple comparison.
7195
7196 // First, handle some easy cases. We know the result cannot be equal at this
7197 // point so handle the ICI.isEquality() cases
7198 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007199 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007201 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007202
7203 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7204 // should have been folded away previously and not enter in here.
7205 Value *Result;
7206 if (isSignedCmp) {
7207 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007208 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007209 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007210 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007211 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007212 } else {
7213 // We're performing an unsigned comparison.
7214 if (isSignedExt) {
7215 // We're performing an unsigned comp with a sign extended value.
7216 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007217 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007218 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007219 } else {
7220 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007221 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007222 }
7223 }
7224
7225 // Finally, return the value computed.
7226 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007227 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007229
7230 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7231 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7232 "ICmp should be folded!");
7233 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007234 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007235 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007236}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007237
Reid Spencer832254e2007-02-02 02:16:23 +00007238Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7239 return commonShiftTransforms(I);
7240}
7241
7242Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7243 return commonShiftTransforms(I);
7244}
7245
7246Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007247 if (Instruction *R = commonShiftTransforms(I))
7248 return R;
7249
7250 Value *Op0 = I.getOperand(0);
7251
7252 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7253 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7254 if (CSI->isAllOnesValue())
7255 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007256
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007257 // See if we can turn a signed shr into an unsigned shr.
7258 if (MaskedValueIsZero(Op0,
7259 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7260 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7261
7262 // Arithmetic shifting an all-sign-bit value is a no-op.
7263 unsigned NumSignBits = ComputeNumSignBits(Op0);
7264 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7265 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007266
Chris Lattner348f6652007-12-06 01:59:46 +00007267 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007268}
7269
7270Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7271 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007273
7274 // shl X, 0 == X and shr X, 0 == X
7275 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007276 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7277 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007278 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007279
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 if (isa<UndefValue>(Op0)) {
7281 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007282 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007283 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007284 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007285 }
7286 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007287 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7288 return ReplaceInstUsesWith(I, Op0);
7289 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007290 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007291 }
7292
Dan Gohman9004c8a2009-05-21 02:28:33 +00007293 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007294 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007295 return &I;
7296
Chris Lattner2eefe512004-04-09 19:05:30 +00007297 // Try to fold constant and into select arguments.
7298 if (isa<Constant>(Op0))
7299 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007300 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007301 return R;
7302
Reid Spencerb83eb642006-10-20 07:07:24 +00007303 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007304 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7305 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007306 return 0;
7307}
7308
Reid Spencerb83eb642006-10-20 07:07:24 +00007309Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007310 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007311 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007312
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007313 // See if we can simplify any instructions used by the instruction whose sole
7314 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007315 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007316
Dan Gohmana119de82009-06-14 23:30:43 +00007317 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7318 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007319 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007320 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007321 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007322 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007323 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007324 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007325 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007326 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007327 }
7328
7329 // ((X*C1) << C2) == (X * (C1 << C2))
7330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7331 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7332 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007333 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007334 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007335
7336 // Try to fold constant and into select arguments.
7337 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7338 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7339 return R;
7340 if (isa<PHINode>(Op0))
7341 if (Instruction *NV = FoldOpIntoPhi(I))
7342 return NV;
7343
Chris Lattner8999dd32007-12-22 09:07:47 +00007344 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7345 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7346 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7347 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7348 // place. Don't try to do this transformation in this case. Also, we
7349 // require that the input operand is a shift-by-constant so that we have
7350 // confidence that the shifts will get folded together. We could do this
7351 // xform in more cases, but it is unlikely to be profitable.
7352 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7353 isa<ConstantInt>(TrOp->getOperand(1))) {
7354 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007355 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007356 // (shift2 (shift1 & 0x00FF), c2)
7357 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007358
7359 // For logical shifts, the truncation has the effect of making the high
7360 // part of the register be zeros. Emulate this by inserting an AND to
7361 // clear the top bits as needed. This 'and' will usually be zapped by
7362 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007363 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7364 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007365 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7366
7367 // The mask we constructed says what the trunc would do if occurring
7368 // between the shifts. We want to know the effect *after* the second
7369 // shift. We know that it is a logical shift by a constant, so adjust the
7370 // mask as appropriate.
7371 if (I.getOpcode() == Instruction::Shl)
7372 MaskV <<= Op1->getZExtValue();
7373 else {
7374 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7375 MaskV = MaskV.lshr(Op1->getZExtValue());
7376 }
7377
Chris Lattner74381062009-08-30 07:44:24 +00007378 // shift1 & 0x00FF
7379 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7380 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007381
7382 // Return the value truncated to the interesting size.
7383 return new TruncInst(And, I.getType());
7384 }
7385 }
7386
Chris Lattner4d5542c2006-01-06 07:12:35 +00007387 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007388 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7389 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7390 Value *V1, *V2;
7391 ConstantInt *CC;
7392 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007393 default: break;
7394 case Instruction::Add:
7395 case Instruction::And:
7396 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007397 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007398 // These operators commute.
7399 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007400 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007401 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007402 m_Specific(Op1)))) {
7403 Value *YS = // (Y << C)
7404 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7405 // (X + (Y << C))
7406 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7407 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007408 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007409 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007410 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007411 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412
Chris Lattner150f12a2005-09-18 06:30:59 +00007413 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007414 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007415 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007416 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007417 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007418 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007419 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007420 Value *YS = // (Y << C)
7421 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7422 Op0BO->getName());
7423 // X & (CC << C)
7424 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7425 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007426 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007427 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007428 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007429
Reid Spencera07cb7d2007-02-02 14:41:37 +00007430 // FALL THROUGH.
7431 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007432 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007433 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007434 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007435 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007436 Value *YS = // (Y << C)
7437 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7438 // (X + (Y << C))
7439 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7440 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007441 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007442 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007443 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007444 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007445
Chris Lattner13d4ab42006-05-31 21:14:00 +00007446 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007447 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7448 match(Op0BO->getOperand(0),
7449 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007450 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007451 cast<BinaryOperator>(Op0BO->getOperand(0))
7452 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007453 Value *YS = // (Y << C)
7454 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7455 // X & (CC << C)
7456 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7457 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007458
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007459 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007460 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007461
Chris Lattner11021cb2005-09-18 05:12:10 +00007462 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007463 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007464 }
7465
7466
7467 // If the operand is an bitwise operator with a constant RHS, and the
7468 // shift is the only use, we can pull it out of the shift.
7469 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7470 bool isValid = true; // Valid only for And, Or, Xor
7471 bool highBitSet = false; // Transform if high bit of constant set?
7472
7473 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007474 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007475 case Instruction::Add:
7476 isValid = isLeftShift;
7477 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007478 case Instruction::Or:
7479 case Instruction::Xor:
7480 highBitSet = false;
7481 break;
7482 case Instruction::And:
7483 highBitSet = true;
7484 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007485 }
7486
7487 // If this is a signed shift right, and the high bit is modified
7488 // by the logical operation, do not perform the transformation.
7489 // The highBitSet boolean indicates the value of the high bit of
7490 // the constant which would cause it to be modified for this
7491 // operation.
7492 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007493 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007494 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007495
7496 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007497 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007498
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007499 Value *NewShift =
7500 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007501 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007502
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007503 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007504 NewRHS);
7505 }
7506 }
7507 }
7508 }
7509
Chris Lattnerad0124c2006-01-06 07:52:12 +00007510 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007511 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7512 if (ShiftOp && !ShiftOp->isShift())
7513 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007514
Reid Spencerb83eb642006-10-20 07:07:24 +00007515 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007516 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007517 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7518 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007519 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7520 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7521 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007522
Zhou Sheng4351c642007-04-02 08:20:41 +00007523 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007524
7525 const IntegerType *Ty = cast<IntegerType>(I.getType());
7526
7527 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007528 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007529 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7530 // saturates.
7531 if (AmtSum >= TypeBits) {
7532 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007533 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007534 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7535 }
7536
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007537 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007538 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007539 }
7540
7541 if (ShiftOp->getOpcode() == Instruction::LShr &&
7542 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007543 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007544 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007545
Chris Lattnerb87056f2007-02-05 00:57:54 +00007546 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007547 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007548 }
7549
7550 if (ShiftOp->getOpcode() == Instruction::AShr &&
7551 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007552 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007553 if (AmtSum >= TypeBits)
7554 AmtSum = TypeBits-1;
7555
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007556 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007557
Zhou Shenge9e03f62007-03-28 15:02:20 +00007558 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007559 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007560 }
7561
Chris Lattnerb87056f2007-02-05 00:57:54 +00007562 // Okay, if we get here, one shift must be left, and the other shift must be
7563 // right. See if the amounts are equal.
7564 if (ShiftAmt1 == ShiftAmt2) {
7565 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7566 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007567 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007568 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007569 }
7570 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7571 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007572 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007573 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007574 }
7575 // We can simplify ((X << C) >>s C) into a trunc + sext.
7576 // NOTE: we could do this for any C, but that would make 'unusual' integer
7577 // types. For now, just stick to ones well-supported by the code
7578 // generators.
7579 const Type *SExtType = 0;
7580 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007581 case 1 :
7582 case 8 :
7583 case 16 :
7584 case 32 :
7585 case 64 :
7586 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007587 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007588 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007589 default: break;
7590 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007591 if (SExtType)
7592 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007593 // Otherwise, we can't handle it yet.
7594 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007595 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007596
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007597 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007598 if (I.getOpcode() == Instruction::Shl) {
7599 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7600 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007601 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007602
Reid Spencer55702aa2007-03-25 21:11:44 +00007603 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007604 return BinaryOperator::CreateAnd(Shift,
7605 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007606 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007607
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007608 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007609 if (I.getOpcode() == Instruction::LShr) {
7610 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007611 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007612
Reid Spencerd5e30f02007-03-26 17:18:58 +00007613 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007614 return BinaryOperator::CreateAnd(Shift,
7615 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007616 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007617
7618 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7619 } else {
7620 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007621 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007622
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007623 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007624 if (I.getOpcode() == Instruction::Shl) {
7625 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7626 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007627 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7628 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007629
Reid Spencer55702aa2007-03-25 21:11:44 +00007630 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007631 return BinaryOperator::CreateAnd(Shift,
7632 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633 }
7634
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007635 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007636 if (I.getOpcode() == Instruction::LShr) {
7637 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007638 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007639
Reid Spencer68d27cf2007-03-26 23:45:51 +00007640 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007641 return BinaryOperator::CreateAnd(Shift,
7642 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007643 }
7644
7645 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007646 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007647 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007648 return 0;
7649}
7650
Chris Lattnera1be5662002-05-02 17:06:02 +00007651
Chris Lattnercfd65102005-10-29 04:36:15 +00007652/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7653/// expression. If so, decompose it, returning some value X, such that Val is
7654/// X*Scale+Offset.
7655///
7656static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007657 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007658 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7659 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007660 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007661 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007662 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007663 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007664 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7665 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7666 if (I->getOpcode() == Instruction::Shl) {
7667 // This is a value scaled by '1 << the shift amt'.
7668 Scale = 1U << RHS->getZExtValue();
7669 Offset = 0;
7670 return I->getOperand(0);
7671 } else if (I->getOpcode() == Instruction::Mul) {
7672 // This value is scaled by 'RHS'.
7673 Scale = RHS->getZExtValue();
7674 Offset = 0;
7675 return I->getOperand(0);
7676 } else if (I->getOpcode() == Instruction::Add) {
7677 // We have X+C. Check to see if we really have (X*C2)+C1,
7678 // where C1 is divisible by C2.
7679 unsigned SubScale;
7680 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007681 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7682 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007683 Offset += RHS->getZExtValue();
7684 Scale = SubScale;
7685 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007686 }
7687 }
7688 }
7689
7690 // Otherwise, we can't look past this.
7691 Scale = 1;
7692 Offset = 0;
7693 return Val;
7694}
7695
7696
Chris Lattnerb3f83972005-10-24 06:03:58 +00007697/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7698/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007699Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007700 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007701 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007702
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007703 BuilderTy AllocaBuilder(*Builder);
7704 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7705
Chris Lattnerb53c2382005-10-24 06:22:12 +00007706 // Remove any uses of AI that are dead.
7707 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007708
Chris Lattnerb53c2382005-10-24 06:22:12 +00007709 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7710 Instruction *User = cast<Instruction>(*UI++);
7711 if (isInstructionTriviallyDead(User)) {
7712 while (UI != E && *UI == User)
7713 ++UI; // If this instruction uses AI more than once, don't break UI.
7714
Chris Lattnerb53c2382005-10-24 06:22:12 +00007715 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007716 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007717 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007718 }
7719 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007720
7721 // This requires TargetData to get the alloca alignment and size information.
7722 if (!TD) return 0;
7723
Chris Lattnerb3f83972005-10-24 06:03:58 +00007724 // Get the type really allocated and the type casted to.
7725 const Type *AllocElTy = AI.getAllocatedType();
7726 const Type *CastElTy = PTy->getElementType();
7727 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007728
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007729 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7730 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007731 if (CastElTyAlign < AllocElTyAlign) return 0;
7732
Chris Lattner39387a52005-10-24 06:35:18 +00007733 // If the allocation has multiple uses, only promote it if we are strictly
7734 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007735 // same, we open the door to infinite loops of various kinds. (A reference
7736 // from a dbg.declare doesn't count as a use for this purpose.)
7737 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7738 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007739
Duncan Sands777d2302009-05-09 07:06:46 +00007740 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7741 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007742 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007743
Chris Lattner455fcc82005-10-29 03:19:53 +00007744 // See if we can satisfy the modulus by pulling a scale out of the array
7745 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007746 unsigned ArraySizeScale;
7747 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007748 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007749 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7750 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007751
Chris Lattner455fcc82005-10-29 03:19:53 +00007752 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7753 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007754 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7755 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007756
Chris Lattner455fcc82005-10-29 03:19:53 +00007757 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7758 Value *Amt = 0;
7759 if (Scale == 1) {
7760 Amt = NumElements;
7761 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007762 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007763 // Insert before the alloca, not before the cast.
7764 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007765 }
7766
Jeff Cohen86796be2007-04-04 16:58:57 +00007767 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007768 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007769 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007770 }
7771
Chris Lattnerb3f83972005-10-24 06:03:58 +00007772 AllocationInst *New;
7773 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007774 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007775 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007776 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7777 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007778 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007779
Dale Johannesena0a66372009-03-05 00:39:02 +00007780 // If the allocation has one real use plus a dbg.declare, just remove the
7781 // declare.
7782 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7783 EraseInstFromFunction(*DI);
7784 }
7785 // If the allocation has multiple real uses, insert a cast and change all
7786 // things that used it to use the new cast. This will also hack on CI, but it
7787 // will die soon.
7788 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007789 // New is the allocation instruction, pointer typed. AI is the original
7790 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007791 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007792 AI.replaceAllUsesWith(NewCast);
7793 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007794 return ReplaceInstUsesWith(CI, New);
7795}
7796
Chris Lattner70074e02006-05-13 02:06:03 +00007797/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007798/// and return it as type Ty without inserting any new casts and without
7799/// changing the computed value. This is used by code that tries to decide
7800/// whether promoting or shrinking integer operations to wider or smaller types
7801/// will allow us to eliminate a truncate or extend.
7802///
7803/// This is a truncation operation if Ty is smaller than V->getType(), or an
7804/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007805///
7806/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7807/// should return true if trunc(V) can be computed by computing V in the smaller
7808/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7809/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7810/// efficiently truncated.
7811///
7812/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7813/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7814/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007815bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007816 unsigned CastOpc,
7817 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007818 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007819 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007820 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007821
7822 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007823 if (!I) return false;
7824
Dan Gohman6de29f82009-06-15 22:12:54 +00007825 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007826
Chris Lattner951626b2007-08-02 06:11:14 +00007827 // If this is an extension or truncate, we can often eliminate it.
7828 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7829 // If this is a cast from the destination type, we can trivially eliminate
7830 // it, and this will remove a cast overall.
7831 if (I->getOperand(0)->getType() == Ty) {
7832 // If the first operand is itself a cast, and is eliminable, do not count
7833 // this as an eliminable cast. We would prefer to eliminate those two
7834 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007835 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007836 ++NumCastsRemoved;
7837 return true;
7838 }
7839 }
7840
7841 // We can't extend or shrink something that has multiple uses: doing so would
7842 // require duplicating the instruction in general, which isn't profitable.
7843 if (!I->hasOneUse()) return false;
7844
Evan Chengf35fd542009-01-15 17:01:23 +00007845 unsigned Opc = I->getOpcode();
7846 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007847 case Instruction::Add:
7848 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007849 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007850 case Instruction::And:
7851 case Instruction::Or:
7852 case Instruction::Xor:
7853 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007854 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007855 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007856 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007857 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007858
Eli Friedman070a9812009-07-13 22:46:01 +00007859 case Instruction::UDiv:
7860 case Instruction::URem: {
7861 // UDiv and URem can be truncated if all the truncated bits are zero.
7862 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7863 uint32_t BitWidth = Ty->getScalarSizeInBits();
7864 if (BitWidth < OrigBitWidth) {
7865 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7866 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7867 MaskedValueIsZero(I->getOperand(1), Mask)) {
7868 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7869 NumCastsRemoved) &&
7870 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7871 NumCastsRemoved);
7872 }
7873 }
7874 break;
7875 }
Chris Lattner46b96052006-11-29 07:18:39 +00007876 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007877 // If we are truncating the result of this SHL, and if it's a shift of a
7878 // constant amount, we can always perform a SHL in a smaller type.
7879 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007880 uint32_t BitWidth = Ty->getScalarSizeInBits();
7881 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007882 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007883 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007884 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007885 }
7886 break;
7887 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007888 // If this is a truncate of a logical shr, we can truncate it to a smaller
7889 // lshr iff we know that the bits we would otherwise be shifting in are
7890 // already zeros.
7891 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007892 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7893 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007894 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007895 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007896 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7897 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007898 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007899 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900 }
7901 }
Chris Lattner46b96052006-11-29 07:18:39 +00007902 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007903 case Instruction::ZExt:
7904 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007905 case Instruction::Trunc:
7906 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007907 // can safely replace it. Note that replacing it does not reduce the number
7908 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007909 if (Opc == CastOpc)
7910 return true;
7911
7912 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007913 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007914 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007915 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007916 case Instruction::Select: {
7917 SelectInst *SI = cast<SelectInst>(I);
7918 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007919 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007920 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007921 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007922 }
Chris Lattner8114b712008-06-18 04:00:49 +00007923 case Instruction::PHI: {
7924 // We can change a phi if we can change all operands.
7925 PHINode *PN = cast<PHINode>(I);
7926 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7927 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007928 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007929 return false;
7930 return true;
7931 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007932 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007933 // TODO: Can handle more cases here.
7934 break;
7935 }
7936
7937 return false;
7938}
7939
7940/// EvaluateInDifferentType - Given an expression that
7941/// CanEvaluateInDifferentType returns true for, actually insert the code to
7942/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007943Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007944 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007945 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007946 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007947 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007948
7949 // Otherwise, it must be an instruction.
7950 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007951 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007952 unsigned Opc = I->getOpcode();
7953 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007954 case Instruction::Add:
7955 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007956 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007957 case Instruction::And:
7958 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007959 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007960 case Instruction::AShr:
7961 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007962 case Instruction::Shl:
7963 case Instruction::UDiv:
7964 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007965 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007966 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007967 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007968 break;
7969 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007970 case Instruction::Trunc:
7971 case Instruction::ZExt:
7972 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007973 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007974 // just return the source. There's no need to insert it because it is not
7975 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007976 if (I->getOperand(0)->getType() == Ty)
7977 return I->getOperand(0);
7978
Chris Lattner8114b712008-06-18 04:00:49 +00007979 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007980 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007981 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007982 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007983 case Instruction::Select: {
7984 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7985 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7986 Res = SelectInst::Create(I->getOperand(0), True, False);
7987 break;
7988 }
Chris Lattner8114b712008-06-18 04:00:49 +00007989 case Instruction::PHI: {
7990 PHINode *OPN = cast<PHINode>(I);
7991 PHINode *NPN = PHINode::Create(Ty);
7992 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7993 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7994 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7995 }
7996 Res = NPN;
7997 break;
7998 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007999 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008000 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008001 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008002 break;
8003 }
8004
Chris Lattner8114b712008-06-18 04:00:49 +00008005 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008006 return InsertNewInstBefore(Res, *I);
8007}
8008
Reid Spencer3da59db2006-11-27 01:05:10 +00008009/// @brief Implement the transforms common to all CastInst visitors.
8010Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008011 Value *Src = CI.getOperand(0);
8012
Dan Gohman23d9d272007-05-11 21:10:54 +00008013 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008014 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008015 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008016 if (Instruction::CastOps opc =
8017 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8018 // The first cast (CSrc) is eliminable so we need to fix up or replace
8019 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008020 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008021 }
8022 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008023
Reid Spencer3da59db2006-11-27 01:05:10 +00008024 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008025 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8026 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8027 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008028
8029 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008030 if (isa<PHINode>(Src))
8031 if (Instruction *NV = FoldOpIntoPhi(CI))
8032 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008033
Reid Spencer3da59db2006-11-27 01:05:10 +00008034 return 0;
8035}
8036
Chris Lattner46cd5a12009-01-09 05:44:56 +00008037/// FindElementAtOffset - Given a type and a constant offset, determine whether
8038/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008039/// the specified offset. If so, fill them into NewIndices and return the
8040/// resultant element type, otherwise return null.
8041static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8042 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008043 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008044 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008045 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008046 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008047
8048 // Start with the index over the outer type. Note that the type size
8049 // might be zero (even if the offset isn't zero) if the indexed type
8050 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008051 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008052 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008053 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008054 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008055 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008056
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008057 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008058 if (Offset < 0) {
8059 --FirstIdx;
8060 Offset += TySize;
8061 assert(Offset >= 0);
8062 }
8063 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8064 }
8065
Owen Andersoneed707b2009-07-24 23:12:02 +00008066 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008067
8068 // Index into the types. If we fail, set OrigBase to null.
8069 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008070 // Indexing into tail padding between struct/array elements.
8071 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008072 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008073
Chris Lattner46cd5a12009-01-09 05:44:56 +00008074 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8075 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008076 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8077 "Offset must stay within the indexed type");
8078
Chris Lattner46cd5a12009-01-09 05:44:56 +00008079 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008080 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008081
8082 Offset -= SL->getElementOffset(Elt);
8083 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008084 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008085 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008086 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008087 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008088 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008089 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008090 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008091 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008092 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008093 }
8094 }
8095
Chris Lattner3914f722009-01-24 01:00:13 +00008096 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008097}
8098
Chris Lattnerd3e28342007-04-27 17:44:50 +00008099/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8100Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8101 Value *Src = CI.getOperand(0);
8102
Chris Lattnerd3e28342007-04-27 17:44:50 +00008103 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008104 // If casting the result of a getelementptr instruction with no offset, turn
8105 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008106 if (GEP->hasAllZeroIndices()) {
8107 // Changing the cast operand is usually not a good idea but it is safe
8108 // here because the pointer operand is being replaced with another
8109 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008110 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008111 CI.setOperand(0, GEP->getOperand(0));
8112 return &CI;
8113 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008114
8115 // If the GEP has a single use, and the base pointer is a bitcast, and the
8116 // GEP computes a constant offset, see if we can convert these three
8117 // instructions into fewer. This typically happens with unions and other
8118 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008119 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008120 if (GEP->hasAllConstantIndices()) {
8121 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008122 ConstantInt *OffsetV =
8123 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008124 int64_t Offset = OffsetV->getSExtValue();
8125
8126 // Get the base pointer input of the bitcast, and the type it points to.
8127 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8128 const Type *GEPIdxTy =
8129 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008130 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008131 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008132 // If we were able to index down into an element, create the GEP
8133 // and bitcast the result. This eliminates one bitcast, potentially
8134 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008135 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8136 Builder->CreateInBoundsGEP(OrigBase,
8137 NewIndices.begin(), NewIndices.end()) :
8138 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008139 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008140
Chris Lattner46cd5a12009-01-09 05:44:56 +00008141 if (isa<BitCastInst>(CI))
8142 return new BitCastInst(NGEP, CI.getType());
8143 assert(isa<PtrToIntInst>(CI));
8144 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008145 }
8146 }
8147 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008148 }
8149
8150 return commonCastTransforms(CI);
8151}
8152
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008153/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8154/// type like i42. We don't want to introduce operations on random non-legal
8155/// integer types where they don't already exist in the code. In the future,
8156/// we should consider making this based off target-data, so that 32-bit targets
8157/// won't get i64 operations etc.
8158static bool isSafeIntegerType(const Type *Ty) {
8159 switch (Ty->getPrimitiveSizeInBits()) {
8160 case 8:
8161 case 16:
8162 case 32:
8163 case 64:
8164 return true;
8165 default:
8166 return false;
8167 }
8168}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008169
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008170/// commonIntCastTransforms - This function implements the common transforms
8171/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008172Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8173 if (Instruction *Result = commonCastTransforms(CI))
8174 return Result;
8175
8176 Value *Src = CI.getOperand(0);
8177 const Type *SrcTy = Src->getType();
8178 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008179 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8180 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008181
Reid Spencer3da59db2006-11-27 01:05:10 +00008182 // See if we can simplify any instructions used by the LHS whose sole
8183 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008184 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008185 return &CI;
8186
8187 // If the source isn't an instruction or has more than one use then we
8188 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008189 Instruction *SrcI = dyn_cast<Instruction>(Src);
8190 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008191 return 0;
8192
Chris Lattnerc739cd62007-03-03 05:27:34 +00008193 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008194 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008195 // Only do this if the dest type is a simple type, don't convert the
8196 // expression tree to something weird like i93 unless the source is also
8197 // strange.
8198 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008199 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8200 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008201 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008202 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008203 // eliminates the cast, so it is always a win. If this is a zero-extension,
8204 // we need to do an AND to maintain the clear top-part of the computation,
8205 // so we require that the input have eliminated at least one cast. If this
8206 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008207 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008208 bool DoXForm = false;
8209 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008210 switch (CI.getOpcode()) {
8211 default:
8212 // All the others use floating point so we shouldn't actually
8213 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008214 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008215 case Instruction::Trunc:
8216 DoXForm = true;
8217 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008218 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008219 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008220 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008221 // If it's unnecessary to issue an AND to clear the high bits, it's
8222 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008223 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008224 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8225 if (MaskedValueIsZero(TryRes, Mask))
8226 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008227
8228 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008229 if (TryI->use_empty())
8230 EraseInstFromFunction(*TryI);
8231 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008232 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008233 }
Evan Chengf35fd542009-01-15 17:01:23 +00008234 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008235 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008236 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008237 // If we do not have to emit the truncate + sext pair, then it's always
8238 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008239 //
8240 // It's not safe to eliminate the trunc + sext pair if one of the
8241 // eliminated cast is a truncate. e.g.
8242 // t2 = trunc i32 t1 to i16
8243 // t3 = sext i16 t2 to i32
8244 // !=
8245 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008246 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008247 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8248 if (NumSignBits > (DestBitSize - SrcBitSize))
8249 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008250
8251 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008252 if (TryI->use_empty())
8253 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008254 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008255 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008256 }
Evan Chengf35fd542009-01-15 17:01:23 +00008257 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008258
8259 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008260 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8261 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008262 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8263 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008264 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008265 // Just replace this cast with the result.
8266 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008267
Reid Spencer3da59db2006-11-27 01:05:10 +00008268 assert(Res->getType() == DestTy);
8269 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008270 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008271 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008272 // Just replace this cast with the result.
8273 return ReplaceInstUsesWith(CI, Res);
8274 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008275 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008276
8277 // If the high bits are already zero, just replace this cast with the
8278 // result.
8279 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8280 if (MaskedValueIsZero(Res, Mask))
8281 return ReplaceInstUsesWith(CI, Res);
8282
8283 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008284 Constant *C = ConstantInt::get(*Context,
8285 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008286 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008287 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008288 case Instruction::SExt: {
8289 // If the high bits are already filled with sign bit, just replace this
8290 // cast with the result.
8291 unsigned NumSignBits = ComputeNumSignBits(Res);
8292 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008293 return ReplaceInstUsesWith(CI, Res);
8294
Reid Spencer3da59db2006-11-27 01:05:10 +00008295 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008296 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008297 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008298 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008299 }
8300 }
8301
8302 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8303 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8304
8305 switch (SrcI->getOpcode()) {
8306 case Instruction::Add:
8307 case Instruction::Mul:
8308 case Instruction::And:
8309 case Instruction::Or:
8310 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008311 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008312 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8313 // Don't insert two casts unless at least one can be eliminated.
8314 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008315 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008316 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8317 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008318 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008319 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008320 }
8321 }
8322
8323 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8324 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8325 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008326 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008327 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008328 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008329 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008330 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008331 }
8332 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008333
Eli Friedman65445c52009-07-13 21:45:57 +00008334 case Instruction::Shl: {
8335 // Canonicalize trunc inside shl, if we can.
8336 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8337 if (CI && DestBitSize < SrcBitSize &&
8338 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008339 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8340 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008341 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008342 }
8343 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008344 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008345 }
8346 return 0;
8347}
8348
Chris Lattner8a9f5712007-04-11 06:57:46 +00008349Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008350 if (Instruction *Result = commonIntCastTransforms(CI))
8351 return Result;
8352
8353 Value *Src = CI.getOperand(0);
8354 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008355 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8356 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008357
8358 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008359 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008360 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008361 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008362 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008363 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008364 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008365
Chris Lattner4f9797d2009-03-24 18:15:30 +00008366 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8367 ConstantInt *ShAmtV = 0;
8368 Value *ShiftOp = 0;
8369 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008370 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008371 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8372
8373 // Get a mask for the bits shifting in.
8374 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8375 if (MaskedValueIsZero(ShiftOp, Mask)) {
8376 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008377 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008378
8379 // Okay, we can shrink this. Truncate the input, then return a new
8380 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008381 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008382 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008383 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008384 }
8385 }
8386
8387 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008388}
8389
Evan Chengb98a10e2008-03-24 00:21:34 +00008390/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8391/// in order to eliminate the icmp.
8392Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8393 bool DoXform) {
8394 // If we are just checking for a icmp eq of a single bit and zext'ing it
8395 // to an integer, then shift the bit to the appropriate place and then
8396 // cast to integer to avoid the comparison.
8397 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8398 const APInt &Op1CV = Op1C->getValue();
8399
8400 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8401 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8402 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8403 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8404 if (!DoXform) return ICI;
8405
8406 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008407 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008408 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008409 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008410 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008411 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008412
8413 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008414 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008415 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008416 }
8417
8418 return ReplaceInstUsesWith(CI, In);
8419 }
8420
8421
8422
8423 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8424 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8425 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8426 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8427 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8428 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8429 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8430 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8431 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8432 // This only works for EQ and NE
8433 ICI->isEquality()) {
8434 // If Op1C some other power of two, convert:
8435 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8436 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8437 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8438 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8439
8440 APInt KnownZeroMask(~KnownZero);
8441 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8442 if (!DoXform) return ICI;
8443
8444 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8445 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8446 // (X&4) == 2 --> false
8447 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008448 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008449 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008450 return ReplaceInstUsesWith(CI, Res);
8451 }
8452
8453 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8454 Value *In = ICI->getOperand(0);
8455 if (ShiftAmt) {
8456 // Perform a logical shr by shiftamt.
8457 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008458 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8459 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008460 }
8461
8462 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008463 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008464 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008465 }
8466
8467 if (CI.getType() == In->getType())
8468 return ReplaceInstUsesWith(CI, In);
8469 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008470 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008471 }
8472 }
8473 }
8474
8475 return 0;
8476}
8477
Chris Lattner8a9f5712007-04-11 06:57:46 +00008478Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008479 // If one of the common conversion will work ..
8480 if (Instruction *Result = commonIntCastTransforms(CI))
8481 return Result;
8482
8483 Value *Src = CI.getOperand(0);
8484
Chris Lattnera84f47c2009-02-17 20:47:23 +00008485 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8486 // types and if the sizes are just right we can convert this into a logical
8487 // 'and' which will be much cheaper than the pair of casts.
8488 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8489 // Get the sizes of the types involved. We know that the intermediate type
8490 // will be smaller than A or C, but don't know the relation between A and C.
8491 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008492 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8493 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8494 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008495 // If we're actually extending zero bits, then if
8496 // SrcSize < DstSize: zext(a & mask)
8497 // SrcSize == DstSize: a & mask
8498 // SrcSize > DstSize: trunc(a) & mask
8499 if (SrcSize < DstSize) {
8500 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008501 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008502 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008503 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008504 }
8505
8506 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008507 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008508 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008509 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008510 }
8511 if (SrcSize > DstSize) {
8512 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008513 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008514 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008515 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008516 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008517 }
8518 }
8519
Evan Chengb98a10e2008-03-24 00:21:34 +00008520 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8521 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008522
Evan Chengb98a10e2008-03-24 00:21:34 +00008523 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8524 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8525 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8526 // of the (zext icmp) will be transformed.
8527 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8528 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8529 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8530 (transformZExtICmp(LHS, CI, false) ||
8531 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008532 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8533 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008534 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008535 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008536 }
8537
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008538 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008539 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8540 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8541 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8542 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008543 if (TI0->getType() == CI.getType())
8544 return
8545 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008546 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008547 }
8548
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008549 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8550 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8551 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8552 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8553 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8554 And->getOperand(1) == C)
8555 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8556 Value *TI0 = TI->getOperand(0);
8557 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008558 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008559 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008560 return BinaryOperator::CreateXor(NewAnd, ZC);
8561 }
8562 }
8563
Reid Spencer3da59db2006-11-27 01:05:10 +00008564 return 0;
8565}
8566
Chris Lattner8a9f5712007-04-11 06:57:46 +00008567Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008568 if (Instruction *I = commonIntCastTransforms(CI))
8569 return I;
8570
Chris Lattner8a9f5712007-04-11 06:57:46 +00008571 Value *Src = CI.getOperand(0);
8572
Dan Gohman1975d032008-10-30 20:40:10 +00008573 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008574 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008575 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008576 Constant::getAllOnesValue(CI.getType()),
8577 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008578
8579 // See if the value being truncated is already sign extended. If so, just
8580 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008581 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008582 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008583 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8584 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8585 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008586 unsigned NumSignBits = ComputeNumSignBits(Op);
8587
8588 if (OpBits == DestBits) {
8589 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8590 // bits, it is already ready.
8591 if (NumSignBits > DestBits-MidBits)
8592 return ReplaceInstUsesWith(CI, Op);
8593 } else if (OpBits < DestBits) {
8594 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8595 // bits, just sext from i32.
8596 if (NumSignBits > OpBits-MidBits)
8597 return new SExtInst(Op, CI.getType(), "tmp");
8598 } else {
8599 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8600 // bits, just truncate to i32.
8601 if (NumSignBits > OpBits-MidBits)
8602 return new TruncInst(Op, CI.getType(), "tmp");
8603 }
8604 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008605
8606 // If the input is a shl/ashr pair of a same constant, then this is a sign
8607 // extension from a smaller value. If we could trust arbitrary bitwidth
8608 // integers, we could turn this into a truncate to the smaller bit and then
8609 // use a sext for the whole extension. Since we don't, look deeper and check
8610 // for a truncate. If the source and dest are the same type, eliminate the
8611 // trunc and extend and just do shifts. For example, turn:
8612 // %a = trunc i32 %i to i8
8613 // %b = shl i8 %a, 6
8614 // %c = ashr i8 %b, 6
8615 // %d = sext i8 %c to i32
8616 // into:
8617 // %a = shl i32 %i, 30
8618 // %d = ashr i32 %a, 30
8619 Value *A = 0;
8620 ConstantInt *BA = 0, *CA = 0;
8621 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008622 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008623 BA == CA && isa<TruncInst>(A)) {
8624 Value *I = cast<TruncInst>(A)->getOperand(0);
8625 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008626 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8627 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008628 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008629 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008630 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008631 return BinaryOperator::CreateAShr(I, ShAmtV);
8632 }
8633 }
8634
Chris Lattnerba417832007-04-11 06:12:58 +00008635 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008636}
8637
Chris Lattnerb7530652008-01-27 05:29:54 +00008638/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8639/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008640static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008641 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008642 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008643 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008644 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8645 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008646 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008647 return 0;
8648}
8649
8650/// LookThroughFPExtensions - If this is an fp extension instruction, look
8651/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008652static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008653 if (Instruction *I = dyn_cast<Instruction>(V))
8654 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008655 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008656
8657 // If this value is a constant, return the constant in the smallest FP type
8658 // that can accurately represent it. This allows us to turn
8659 // (float)((double)X+2.0) into x+2.0f.
8660 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008661 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008662 return V; // No constant folding of this.
8663 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008664 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008665 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008666 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008667 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008668 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008669 return V;
8670 // Don't try to shrink to various long double types.
8671 }
8672
8673 return V;
8674}
8675
8676Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8677 if (Instruction *I = commonCastTransforms(CI))
8678 return I;
8679
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008680 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008681 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008682 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008683 // many builtins (sqrt, etc).
8684 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8685 if (OpI && OpI->hasOneUse()) {
8686 switch (OpI->getOpcode()) {
8687 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008688 case Instruction::FAdd:
8689 case Instruction::FSub:
8690 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008691 case Instruction::FDiv:
8692 case Instruction::FRem:
8693 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008694 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8695 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008696 if (LHSTrunc->getType() != SrcTy &&
8697 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008698 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008699 // If the source types were both smaller than the destination type of
8700 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008701 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8702 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008703 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8704 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008705 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008706 }
8707 }
8708 break;
8709 }
8710 }
8711 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008712}
8713
8714Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8715 return commonCastTransforms(CI);
8716}
8717
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008718Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008719 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8720 if (OpI == 0)
8721 return commonCastTransforms(FI);
8722
8723 // fptoui(uitofp(X)) --> X
8724 // fptoui(sitofp(X)) --> X
8725 // This is safe if the intermediate type has enough bits in its mantissa to
8726 // accurately represent all values of X. For example, do not do this with
8727 // i64->float->i64. This is also safe for sitofp case, because any negative
8728 // 'X' value would cause an undefined result for the fptoui.
8729 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8730 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008731 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008732 OpI->getType()->getFPMantissaWidth())
8733 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008734
8735 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008736}
8737
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008738Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008739 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8740 if (OpI == 0)
8741 return commonCastTransforms(FI);
8742
8743 // fptosi(sitofp(X)) --> X
8744 // fptosi(uitofp(X)) --> X
8745 // This is safe if the intermediate type has enough bits in its mantissa to
8746 // accurately represent all values of X. For example, do not do this with
8747 // i64->float->i64. This is also safe for sitofp case, because any negative
8748 // 'X' value would cause an undefined result for the fptoui.
8749 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8750 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008751 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008752 OpI->getType()->getFPMantissaWidth())
8753 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008754
8755 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008756}
8757
8758Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8759 return commonCastTransforms(CI);
8760}
8761
8762Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8763 return commonCastTransforms(CI);
8764}
8765
Chris Lattnera0e69692009-03-24 18:35:40 +00008766Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8767 // If the destination integer type is smaller than the intptr_t type for
8768 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8769 // trunc to be exposed to other transforms. Don't do this for extending
8770 // ptrtoint's, because we don't know if the target sign or zero extends its
8771 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008772 if (TD &&
8773 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008774 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8775 TD->getIntPtrType(CI.getContext()),
8776 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008777 return new TruncInst(P, CI.getType());
8778 }
8779
Chris Lattnerd3e28342007-04-27 17:44:50 +00008780 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008781}
8782
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008783Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008784 // If the source integer type is larger than the intptr_t type for
8785 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8786 // allows the trunc to be exposed to other transforms. Don't do this for
8787 // extending inttoptr's, because we don't know if the target sign or zero
8788 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008789 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008790 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008791 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8792 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008793 return new IntToPtrInst(P, CI.getType());
8794 }
8795
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008796 if (Instruction *I = commonCastTransforms(CI))
8797 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008798
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008799 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008800}
8801
Chris Lattnerd3e28342007-04-27 17:44:50 +00008802Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008803 // If the operands are integer typed then apply the integer transforms,
8804 // otherwise just apply the common ones.
8805 Value *Src = CI.getOperand(0);
8806 const Type *SrcTy = Src->getType();
8807 const Type *DestTy = CI.getType();
8808
Eli Friedman7e25d452009-07-13 20:53:00 +00008809 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008810 if (Instruction *I = commonPointerCastTransforms(CI))
8811 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008812 } else {
8813 if (Instruction *Result = commonCastTransforms(CI))
8814 return Result;
8815 }
8816
8817
8818 // Get rid of casts from one type to the same type. These are useless and can
8819 // be replaced by the operand.
8820 if (DestTy == Src->getType())
8821 return ReplaceInstUsesWith(CI, Src);
8822
Reid Spencer3da59db2006-11-27 01:05:10 +00008823 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008824 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8825 const Type *DstElTy = DstPTy->getElementType();
8826 const Type *SrcElTy = SrcPTy->getElementType();
8827
Nate Begeman83ad90a2008-03-31 00:22:16 +00008828 // If the address spaces don't match, don't eliminate the bitcast, which is
8829 // required for changing types.
8830 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8831 return 0;
8832
Victor Hernandez83d63912009-09-18 22:35:49 +00008833 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008834 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008835 // There is no need to modify malloc calls because it is their bitcast that
8836 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008837 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8838 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8839 return V;
8840
Chris Lattnerd717c182007-05-05 22:32:24 +00008841 // If the source and destination are pointers, and this cast is equivalent
8842 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008843 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008844 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008845 unsigned NumZeros = 0;
8846 while (SrcElTy != DstElTy &&
8847 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8848 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8849 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8850 ++NumZeros;
8851 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008852
Chris Lattnerd3e28342007-04-27 17:44:50 +00008853 // If we found a path from the src to dest, create the getelementptr now.
8854 if (SrcElTy == DstElTy) {
8855 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008856 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8857 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008858 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008859 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008860
Eli Friedman2451a642009-07-18 23:06:53 +00008861 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8862 if (DestVTy->getNumElements() == 1) {
8863 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008864 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008865 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008866 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008867 }
8868 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8869 }
8870 }
8871
8872 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8873 if (SrcVTy->getNumElements() == 1) {
8874 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008875 Value *Elem =
8876 Builder->CreateExtractElement(Src,
8877 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008878 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8879 }
8880 }
8881 }
8882
Reid Spencer3da59db2006-11-27 01:05:10 +00008883 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8884 if (SVI->hasOneUse()) {
8885 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8886 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008887 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008888 cast<VectorType>(DestTy)->getNumElements() ==
8889 SVI->getType()->getNumElements() &&
8890 SVI->getType()->getNumElements() ==
8891 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008892 CastInst *Tmp;
8893 // If either of the operands is a cast from CI.getType(), then
8894 // evaluating the shuffle in the casted destination's type will allow
8895 // us to eliminate at least one cast.
8896 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8897 Tmp->getOperand(0)->getType() == DestTy) ||
8898 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8899 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008900 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8901 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008902 // Return a new shuffle vector. Use the same element ID's, as we
8903 // know the vector types match #elts.
8904 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008905 }
8906 }
8907 }
8908 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008909 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008910}
8911
Chris Lattnere576b912004-04-09 23:46:01 +00008912/// GetSelectFoldableOperands - We want to turn code that looks like this:
8913/// %C = or %A, %B
8914/// %D = select %cond, %C, %A
8915/// into:
8916/// %C = select %cond, %B, 0
8917/// %D = or %A, %C
8918///
8919/// Assuming that the specified instruction is an operand to the select, return
8920/// a bitmask indicating which operands of this instruction are foldable if they
8921/// equal the other incoming value of the select.
8922///
8923static unsigned GetSelectFoldableOperands(Instruction *I) {
8924 switch (I->getOpcode()) {
8925 case Instruction::Add:
8926 case Instruction::Mul:
8927 case Instruction::And:
8928 case Instruction::Or:
8929 case Instruction::Xor:
8930 return 3; // Can fold through either operand.
8931 case Instruction::Sub: // Can only fold on the amount subtracted.
8932 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008933 case Instruction::LShr:
8934 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008935 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008936 default:
8937 return 0; // Cannot fold
8938 }
8939}
8940
8941/// GetSelectFoldableConstant - For the same transformation as the previous
8942/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008943static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008944 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008945 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008946 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008947 case Instruction::Add:
8948 case Instruction::Sub:
8949 case Instruction::Or:
8950 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008951 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008952 case Instruction::LShr:
8953 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008954 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008955 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008956 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008957 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008958 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008959 }
8960}
8961
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008962/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8963/// have the same opcode and only one use each. Try to simplify this.
8964Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8965 Instruction *FI) {
8966 if (TI->getNumOperands() == 1) {
8967 // If this is a non-volatile load or a cast from the same type,
8968 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008969 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008970 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8971 return 0;
8972 } else {
8973 return 0; // unknown unary op.
8974 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008975
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008976 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008977 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008978 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008979 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008980 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008981 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008982 }
8983
Reid Spencer832254e2007-02-02 02:16:23 +00008984 // Only handle binary operators here.
8985 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008986 return 0;
8987
8988 // Figure out if the operations have any operands in common.
8989 Value *MatchOp, *OtherOpT, *OtherOpF;
8990 bool MatchIsOpZero;
8991 if (TI->getOperand(0) == FI->getOperand(0)) {
8992 MatchOp = TI->getOperand(0);
8993 OtherOpT = TI->getOperand(1);
8994 OtherOpF = FI->getOperand(1);
8995 MatchIsOpZero = true;
8996 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8997 MatchOp = TI->getOperand(1);
8998 OtherOpT = TI->getOperand(0);
8999 OtherOpF = FI->getOperand(0);
9000 MatchIsOpZero = false;
9001 } else if (!TI->isCommutative()) {
9002 return 0;
9003 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9004 MatchOp = TI->getOperand(0);
9005 OtherOpT = TI->getOperand(1);
9006 OtherOpF = FI->getOperand(0);
9007 MatchIsOpZero = true;
9008 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9009 MatchOp = TI->getOperand(1);
9010 OtherOpT = TI->getOperand(0);
9011 OtherOpF = FI->getOperand(1);
9012 MatchIsOpZero = true;
9013 } else {
9014 return 0;
9015 }
9016
9017 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009018 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9019 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009020 InsertNewInstBefore(NewSI, SI);
9021
9022 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9023 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009024 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009025 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009026 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009027 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009028 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009029 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009030}
9031
Evan Chengde621922009-03-31 20:42:45 +00009032static bool isSelect01(Constant *C1, Constant *C2) {
9033 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9034 if (!C1I)
9035 return false;
9036 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9037 if (!C2I)
9038 return false;
9039 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9040}
9041
9042/// FoldSelectIntoOp - Try fold the select into one of the operands to
9043/// facilitate further optimization.
9044Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9045 Value *FalseVal) {
9046 // See the comment above GetSelectFoldableOperands for a description of the
9047 // transformation we are doing here.
9048 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9049 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9050 !isa<Constant>(FalseVal)) {
9051 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9052 unsigned OpToFold = 0;
9053 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9054 OpToFold = 1;
9055 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9056 OpToFold = 2;
9057 }
9058
9059 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009060 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009061 Value *OOp = TVI->getOperand(2-OpToFold);
9062 // Avoid creating select between 2 constants unless it's selecting
9063 // between 0 and 1.
9064 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9065 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9066 InsertNewInstBefore(NewSel, SI);
9067 NewSel->takeName(TVI);
9068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9069 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009070 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009071 }
9072 }
9073 }
9074 }
9075 }
9076
9077 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9078 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9079 !isa<Constant>(TrueVal)) {
9080 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9081 unsigned OpToFold = 0;
9082 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9083 OpToFold = 1;
9084 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9085 OpToFold = 2;
9086 }
9087
9088 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009089 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009090 Value *OOp = FVI->getOperand(2-OpToFold);
9091 // Avoid creating select between 2 constants unless it's selecting
9092 // between 0 and 1.
9093 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9094 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9095 InsertNewInstBefore(NewSel, SI);
9096 NewSel->takeName(FVI);
9097 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9098 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009099 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009100 }
9101 }
9102 }
9103 }
9104 }
9105
9106 return 0;
9107}
9108
Dan Gohman81b28ce2008-09-16 18:46:06 +00009109/// visitSelectInstWithICmp - Visit a SelectInst that has an
9110/// ICmpInst as its first operand.
9111///
9112Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9113 ICmpInst *ICI) {
9114 bool Changed = false;
9115 ICmpInst::Predicate Pred = ICI->getPredicate();
9116 Value *CmpLHS = ICI->getOperand(0);
9117 Value *CmpRHS = ICI->getOperand(1);
9118 Value *TrueVal = SI.getTrueValue();
9119 Value *FalseVal = SI.getFalseValue();
9120
9121 // Check cases where the comparison is with a constant that
9122 // can be adjusted to fit the min/max idiom. We may edit ICI in
9123 // place here, so make sure the select is the only user.
9124 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009125 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009126 switch (Pred) {
9127 default: break;
9128 case ICmpInst::ICMP_ULT:
9129 case ICmpInst::ICMP_SLT: {
9130 // X < MIN ? T : F --> F
9131 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9132 return ReplaceInstUsesWith(SI, FalseVal);
9133 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009134 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009135 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9136 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9137 Pred = ICmpInst::getSwappedPredicate(Pred);
9138 CmpRHS = AdjustedRHS;
9139 std::swap(FalseVal, TrueVal);
9140 ICI->setPredicate(Pred);
9141 ICI->setOperand(1, CmpRHS);
9142 SI.setOperand(1, TrueVal);
9143 SI.setOperand(2, FalseVal);
9144 Changed = true;
9145 }
9146 break;
9147 }
9148 case ICmpInst::ICMP_UGT:
9149 case ICmpInst::ICMP_SGT: {
9150 // X > MAX ? T : F --> F
9151 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9152 return ReplaceInstUsesWith(SI, FalseVal);
9153 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009154 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009155 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9156 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9157 Pred = ICmpInst::getSwappedPredicate(Pred);
9158 CmpRHS = AdjustedRHS;
9159 std::swap(FalseVal, TrueVal);
9160 ICI->setPredicate(Pred);
9161 ICI->setOperand(1, CmpRHS);
9162 SI.setOperand(1, TrueVal);
9163 SI.setOperand(2, FalseVal);
9164 Changed = true;
9165 }
9166 break;
9167 }
9168 }
9169
Dan Gohman1975d032008-10-30 20:40:10 +00009170 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9171 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009172 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009173 if (match(TrueVal, m_ConstantInt<-1>()) &&
9174 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009175 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009176 else if (match(TrueVal, m_ConstantInt<0>()) &&
9177 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009178 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9179
Dan Gohman1975d032008-10-30 20:40:10 +00009180 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9181 // If we are just checking for a icmp eq of a single bit and zext'ing it
9182 // to an integer, then shift the bit to the appropriate place and then
9183 // cast to integer to avoid the comparison.
9184 const APInt &Op1CV = CI->getValue();
9185
9186 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9187 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9188 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009189 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009190 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009191 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009192 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009193 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009194 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009195 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009196 if (In->getType() != SI.getType())
9197 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009198 true/*SExt*/, "tmp", ICI);
9199
9200 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009201 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009202 In->getName()+".not"), *ICI);
9203
9204 return ReplaceInstUsesWith(SI, In);
9205 }
9206 }
9207 }
9208
Dan Gohman81b28ce2008-09-16 18:46:06 +00009209 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9210 // Transform (X == Y) ? X : Y -> Y
9211 if (Pred == ICmpInst::ICMP_EQ)
9212 return ReplaceInstUsesWith(SI, FalseVal);
9213 // Transform (X != Y) ? X : Y -> X
9214 if (Pred == ICmpInst::ICMP_NE)
9215 return ReplaceInstUsesWith(SI, TrueVal);
9216 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9217
9218 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9219 // Transform (X == Y) ? Y : X -> X
9220 if (Pred == ICmpInst::ICMP_EQ)
9221 return ReplaceInstUsesWith(SI, FalseVal);
9222 // Transform (X != Y) ? Y : X -> Y
9223 if (Pred == ICmpInst::ICMP_NE)
9224 return ReplaceInstUsesWith(SI, TrueVal);
9225 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9226 }
9227
9228 /// NOTE: if we wanted to, this is where to detect integer ABS
9229
9230 return Changed ? &SI : 0;
9231}
9232
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009233/// isDefinedInBB - Return true if the value is an instruction defined in the
9234/// specified basicblock.
9235static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9236 const Instruction *I = dyn_cast<Instruction>(V);
9237 return I != 0 && I->getParent() == BB;
9238}
9239
9240
Chris Lattner3d69f462004-03-12 05:52:32 +00009241Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009242 Value *CondVal = SI.getCondition();
9243 Value *TrueVal = SI.getTrueValue();
9244 Value *FalseVal = SI.getFalseValue();
9245
9246 // select true, X, Y -> X
9247 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009248 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009249 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009250
9251 // select C, X, X -> X
9252 if (TrueVal == FalseVal)
9253 return ReplaceInstUsesWith(SI, TrueVal);
9254
Chris Lattnere87597f2004-10-16 18:11:37 +00009255 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9256 return ReplaceInstUsesWith(SI, FalseVal);
9257 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9258 return ReplaceInstUsesWith(SI, TrueVal);
9259 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9260 if (isa<Constant>(TrueVal))
9261 return ReplaceInstUsesWith(SI, TrueVal);
9262 else
9263 return ReplaceInstUsesWith(SI, FalseVal);
9264 }
9265
Owen Anderson1d0be152009-08-13 21:58:54 +00009266 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009267 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009268 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009269 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009270 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009271 } else {
9272 // Change: A = select B, false, C --> A = and !B, C
9273 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009274 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009275 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009276 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009277 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009278 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009279 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009280 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009281 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009282 } else {
9283 // Change: A = select B, C, true --> A = or !B, C
9284 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009285 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009286 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009287 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009288 }
9289 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009290
9291 // select a, b, a -> a&b
9292 // select a, a, b -> a|b
9293 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009294 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009295 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009296 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009297 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009298
Chris Lattner2eefe512004-04-09 19:05:30 +00009299 // Selecting between two integer constants?
9300 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9301 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009302 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009303 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009304 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009305 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009306 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009307 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009308 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009309 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009310 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009311 }
Chris Lattner457dd822004-06-09 07:59:58 +00009312
Reid Spencere4d87aa2006-12-23 06:05:41 +00009313 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009314 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009315 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009316 // non-constant value, eliminate this whole mess. This corresponds to
9317 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009318 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009319 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009320 cast<Constant>(IC->getOperand(1))->isNullValue())
9321 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9322 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009323 isa<ConstantInt>(ICA->getOperand(1)) &&
9324 (ICA->getOperand(1) == TrueValC ||
9325 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009326 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9327 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009328 // know whether we have a icmp_ne or icmp_eq and whether the
9329 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009330 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009331 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009332 Value *V = ICA;
9333 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009334 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009335 Instruction::Xor, V, ICA->getOperand(1)), SI);
9336 return ReplaceInstUsesWith(SI, V);
9337 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009338 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009339 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009340
9341 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009342 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9343 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009344 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009345 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9346 // This is not safe in general for floating point:
9347 // consider X== -0, Y== +0.
9348 // It becomes safe if either operand is a nonzero constant.
9349 ConstantFP *CFPt, *CFPf;
9350 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9351 !CFPt->getValueAPF().isZero()) ||
9352 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9353 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009354 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009355 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009356 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009357 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009358 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009359 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009360
Reid Spencere4d87aa2006-12-23 06:05:41 +00009361 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009362 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009363 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9364 // This is not safe in general for floating point:
9365 // consider X== -0, Y== +0.
9366 // It becomes safe if either operand is a nonzero constant.
9367 ConstantFP *CFPt, *CFPf;
9368 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9369 !CFPt->getValueAPF().isZero()) ||
9370 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9371 !CFPf->getValueAPF().isZero()))
9372 return ReplaceInstUsesWith(SI, FalseVal);
9373 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009374 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009375 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9376 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009377 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009378 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009379 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009380 }
9381
9382 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009383 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9384 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9385 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009386
Chris Lattner87875da2005-01-13 22:52:24 +00009387 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9388 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9389 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009390 Instruction *AddOp = 0, *SubOp = 0;
9391
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009392 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9393 if (TI->getOpcode() == FI->getOpcode())
9394 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9395 return IV;
9396
9397 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9398 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009399 if ((TI->getOpcode() == Instruction::Sub &&
9400 FI->getOpcode() == Instruction::Add) ||
9401 (TI->getOpcode() == Instruction::FSub &&
9402 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009403 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009404 } else if ((FI->getOpcode() == Instruction::Sub &&
9405 TI->getOpcode() == Instruction::Add) ||
9406 (FI->getOpcode() == Instruction::FSub &&
9407 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009408 AddOp = TI; SubOp = FI;
9409 }
9410
9411 if (AddOp) {
9412 Value *OtherAddOp = 0;
9413 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9414 OtherAddOp = AddOp->getOperand(1);
9415 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9416 OtherAddOp = AddOp->getOperand(0);
9417 }
9418
9419 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009420 // So at this point we know we have (Y -> OtherAddOp):
9421 // select C, (add X, Y), (sub X, Z)
9422 Value *NegVal; // Compute -Z
9423 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009424 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009425 } else {
9426 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009427 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009428 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009429 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009430
9431 Value *NewTrueOp = OtherAddOp;
9432 Value *NewFalseOp = NegVal;
9433 if (AddOp != TI)
9434 std::swap(NewTrueOp, NewFalseOp);
9435 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009436 SelectInst::Create(CondVal, NewTrueOp,
9437 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009438
9439 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009440 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009441 }
9442 }
9443 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009444
Chris Lattnere576b912004-04-09 23:46:01 +00009445 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009446 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009447 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9448 if (FoldI)
9449 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009450 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009451
Chris Lattner5d1704d2009-09-27 19:57:57 +00009452 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009453 // to be live in the predecessor blocks. If they are instructions in SI's
9454 // block, we can't map to the predecessor.
Chris Lattner5d1704d2009-09-27 19:57:57 +00009455 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009456 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9457 isa<PHINode>(SI.getTrueValue())) &&
9458 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9459 isa<PHINode>(SI.getFalseValue())))
Chris Lattner5d1704d2009-09-27 19:57:57 +00009460 if (Instruction *NV = FoldOpIntoPhi(SI))
9461 return NV;
9462
Chris Lattnera1df33c2005-04-24 07:30:14 +00009463 if (BinaryOperator::isNot(CondVal)) {
9464 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9465 SI.setOperand(1, FalseVal);
9466 SI.setOperand(2, TrueVal);
9467 return &SI;
9468 }
9469
Chris Lattner3d69f462004-03-12 05:52:32 +00009470 return 0;
9471}
9472
Dan Gohmaneee962e2008-04-10 18:43:06 +00009473/// EnforceKnownAlignment - If the specified pointer points to an object that
9474/// we control, modify the object's alignment to PrefAlign. This isn't
9475/// often possible though. If alignment is important, a more reliable approach
9476/// is to simply align all global variables and allocation instructions to
9477/// their preferred alignment from the beginning.
9478///
9479static unsigned EnforceKnownAlignment(Value *V,
9480 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009481
Dan Gohmaneee962e2008-04-10 18:43:06 +00009482 User *U = dyn_cast<User>(V);
9483 if (!U) return Align;
9484
Dan Gohmanca178902009-07-17 20:47:02 +00009485 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009486 default: break;
9487 case Instruction::BitCast:
9488 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9489 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009490 // If all indexes are zero, it is just the alignment of the base pointer.
9491 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009492 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009493 if (!isa<Constant>(*i) ||
9494 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009495 AllZeroOperands = false;
9496 break;
9497 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009498
9499 if (AllZeroOperands) {
9500 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009501 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009502 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009503 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009504 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009505 }
9506
9507 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9508 // If there is a large requested alignment and we can, bump up the alignment
9509 // of the global.
9510 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009511 if (GV->getAlignment() >= PrefAlign)
9512 Align = GV->getAlignment();
9513 else {
9514 GV->setAlignment(PrefAlign);
9515 Align = PrefAlign;
9516 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009517 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009518 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9519 // If there is a requested alignment and if this is an alloca, round up.
9520 if (AI->getAlignment() >= PrefAlign)
9521 Align = AI->getAlignment();
9522 else {
9523 AI->setAlignment(PrefAlign);
9524 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009525 }
9526 }
9527
9528 return Align;
9529}
9530
9531/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9532/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9533/// and it is more than the alignment of the ultimate object, see if we can
9534/// increase the alignment of the ultimate object, making this check succeed.
9535unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9536 unsigned PrefAlign) {
9537 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9538 sizeof(PrefAlign) * CHAR_BIT;
9539 APInt Mask = APInt::getAllOnesValue(BitWidth);
9540 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9541 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9542 unsigned TrailZ = KnownZero.countTrailingOnes();
9543 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9544
9545 if (PrefAlign > Align)
9546 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9547
9548 // We don't need to make any adjustment.
9549 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009550}
9551
Chris Lattnerf497b022008-01-13 23:50:23 +00009552Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009553 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009554 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009555 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009556 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009557
9558 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009559 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009560 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009561 return MI;
9562 }
9563
9564 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9565 // load/store.
9566 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9567 if (MemOpLength == 0) return 0;
9568
Chris Lattner37ac6082008-01-14 00:28:35 +00009569 // Source and destination pointer types are always "i8*" for intrinsic. See
9570 // if the size is something we can handle with a single primitive load/store.
9571 // A single load+store correctly handles overlapping memory in the memmove
9572 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009573 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009574 if (Size == 0) return MI; // Delete this mem transfer.
9575
9576 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009577 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009578
Chris Lattner37ac6082008-01-14 00:28:35 +00009579 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009580 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009581 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009582
9583 // Memcpy forces the use of i8* for the source and destination. That means
9584 // that if you're using memcpy to move one double around, you'll get a cast
9585 // from double* to i8*. We'd much rather use a double load+store rather than
9586 // an i64 load+store, here because this improves the odds that the source or
9587 // dest address will be promotable. See if we can find a better type than the
9588 // integer datatype.
9589 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9590 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009591 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009592 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9593 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009594 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009595 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9596 if (STy->getNumElements() == 1)
9597 SrcETy = STy->getElementType(0);
9598 else
9599 break;
9600 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9601 if (ATy->getNumElements() == 1)
9602 SrcETy = ATy->getElementType();
9603 else
9604 break;
9605 } else
9606 break;
9607 }
9608
Dan Gohman8f8e2692008-05-23 01:52:21 +00009609 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009610 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009611 }
9612 }
9613
9614
Chris Lattnerf497b022008-01-13 23:50:23 +00009615 // If the memcpy/memmove provides better alignment info than we can
9616 // infer, use it.
9617 SrcAlign = std::max(SrcAlign, CopyAlign);
9618 DstAlign = std::max(DstAlign, CopyAlign);
9619
Chris Lattner08142f22009-08-30 19:47:22 +00009620 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9621 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009622 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9623 InsertNewInstBefore(L, *MI);
9624 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9625
9626 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009627 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009628 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009629}
Chris Lattner3d69f462004-03-12 05:52:32 +00009630
Chris Lattner69ea9d22008-04-30 06:39:11 +00009631Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9632 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009633 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009634 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009635 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009636 return MI;
9637 }
9638
9639 // Extract the length and alignment and fill if they are constant.
9640 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9641 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009642 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009643 return 0;
9644 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009645 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009646
9647 // If the length is zero, this is a no-op
9648 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9649
9650 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9651 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009652 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009653
9654 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009655 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009656
9657 // Alignment 0 is identity for alignment 1 for memset, but not store.
9658 if (Alignment == 0) Alignment = 1;
9659
9660 // Extract the fill value and store.
9661 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009662 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009663 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009664
9665 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009666 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009667 return MI;
9668 }
9669
9670 return 0;
9671}
9672
9673
Chris Lattner8b0ea312006-01-13 20:11:04 +00009674/// visitCallInst - CallInst simplification. This mostly only handles folding
9675/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9676/// the heavy lifting.
9677///
Chris Lattner9fe38862003-06-19 17:00:31 +00009678Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009679 // If the caller function is nounwind, mark the call as nounwind, even if the
9680 // callee isn't.
9681 if (CI.getParent()->getParent()->doesNotThrow() &&
9682 !CI.doesNotThrow()) {
9683 CI.setDoesNotThrow();
9684 return &CI;
9685 }
9686
Chris Lattner8b0ea312006-01-13 20:11:04 +00009687 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9688 if (!II) return visitCallSite(&CI);
9689
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009690 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9691 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009692 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009693 bool Changed = false;
9694
9695 // memmove/cpy/set of zero bytes is a noop.
9696 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9697 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9698
Chris Lattner35b9e482004-10-12 04:52:52 +00009699 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009700 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009701 // Replace the instruction with just byte operations. We would
9702 // transform other cases to loads/stores, but we don't know if
9703 // alignment is sufficient.
9704 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009705 }
9706
Chris Lattner35b9e482004-10-12 04:52:52 +00009707 // If we have a memmove and the source operation is a constant global,
9708 // then the source and dest pointers can't alias, so we can change this
9709 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009710 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009711 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9712 if (GVSrc->isConstant()) {
9713 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009714 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9715 const Type *Tys[1];
9716 Tys[0] = CI.getOperand(3)->getType();
9717 CI.setOperand(0,
9718 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009719 Changed = true;
9720 }
Chris Lattnera935db82008-05-28 05:30:41 +00009721
9722 // memmove(x,x,size) -> noop.
9723 if (MMI->getSource() == MMI->getDest())
9724 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009725 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009726
Chris Lattner95a959d2006-03-06 20:18:44 +00009727 // If we can determine a pointer alignment that is bigger than currently
9728 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009729 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009730 if (Instruction *I = SimplifyMemTransfer(MI))
9731 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009732 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9733 if (Instruction *I = SimplifyMemSet(MSI))
9734 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009735 }
9736
Chris Lattner8b0ea312006-01-13 20:11:04 +00009737 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009738 }
9739
9740 switch (II->getIntrinsicID()) {
9741 default: break;
9742 case Intrinsic::bswap:
9743 // bswap(bswap(x)) -> x
9744 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9745 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9746 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9747 break;
9748 case Intrinsic::ppc_altivec_lvx:
9749 case Intrinsic::ppc_altivec_lvxl:
9750 case Intrinsic::x86_sse_loadu_ps:
9751 case Intrinsic::x86_sse2_loadu_pd:
9752 case Intrinsic::x86_sse2_loadu_dq:
9753 // Turn PPC lvx -> load if the pointer is known aligned.
9754 // Turn X86 loadups -> load if the pointer is known aligned.
9755 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009756 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9757 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009758 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009759 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009760 break;
9761 case Intrinsic::ppc_altivec_stvx:
9762 case Intrinsic::ppc_altivec_stvxl:
9763 // Turn stvx -> store if the pointer is known aligned.
9764 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9765 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009766 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009767 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009768 return new StoreInst(II->getOperand(1), Ptr);
9769 }
9770 break;
9771 case Intrinsic::x86_sse_storeu_ps:
9772 case Intrinsic::x86_sse2_storeu_pd:
9773 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009774 // Turn X86 storeu -> store if the pointer is known aligned.
9775 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9776 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009777 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009778 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009779 return new StoreInst(II->getOperand(2), Ptr);
9780 }
9781 break;
9782
9783 case Intrinsic::x86_sse_cvttss2si: {
9784 // These intrinsics only demands the 0th element of its input vector. If
9785 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009786 unsigned VWidth =
9787 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9788 APInt DemandedElts(VWidth, 1);
9789 APInt UndefElts(VWidth, 0);
9790 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009791 UndefElts)) {
9792 II->setOperand(1, V);
9793 return II;
9794 }
9795 break;
9796 }
9797
9798 case Intrinsic::ppc_altivec_vperm:
9799 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9800 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9801 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009802
Chris Lattner0521e3c2008-06-18 04:33:20 +00009803 // Check that all of the elements are integer constants or undefs.
9804 bool AllEltsOk = true;
9805 for (unsigned i = 0; i != 16; ++i) {
9806 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9807 !isa<UndefValue>(Mask->getOperand(i))) {
9808 AllEltsOk = false;
9809 break;
9810 }
9811 }
9812
9813 if (AllEltsOk) {
9814 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009815 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9816 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009817 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009818
Chris Lattner0521e3c2008-06-18 04:33:20 +00009819 // Only extract each element once.
9820 Value *ExtractedElts[32];
9821 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9822
Chris Lattnere2ed0572006-04-06 19:19:17 +00009823 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009824 if (isa<UndefValue>(Mask->getOperand(i)))
9825 continue;
9826 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9827 Idx &= 31; // Match the hardware behavior.
9828
9829 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009830 ExtractedElts[Idx] =
9831 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9832 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9833 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009834 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009835
Chris Lattner0521e3c2008-06-18 04:33:20 +00009836 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009837 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9838 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9839 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009840 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009841 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009842 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009843 }
9844 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009845
Chris Lattner0521e3c2008-06-18 04:33:20 +00009846 case Intrinsic::stackrestore: {
9847 // If the save is right next to the restore, remove the restore. This can
9848 // happen when variable allocas are DCE'd.
9849 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9850 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9851 BasicBlock::iterator BI = SS;
9852 if (&*++BI == II)
9853 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009854 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009855 }
9856
9857 // Scan down this block to see if there is another stack restore in the
9858 // same block without an intervening call/alloca.
9859 BasicBlock::iterator BI = II;
9860 TerminatorInst *TI = II->getParent()->getTerminator();
9861 bool CannotRemove = false;
9862 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009863 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 CannotRemove = true;
9865 break;
9866 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009867 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9868 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9869 // If there is a stackrestore below this one, remove this one.
9870 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9871 return EraseInstFromFunction(CI);
9872 // Otherwise, ignore the intrinsic.
9873 } else {
9874 // If we found a non-intrinsic call, we can't remove the stack
9875 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009876 CannotRemove = true;
9877 break;
9878 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009879 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009880 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009881
9882 // If the stack restore is in a return/unwind block and if there are no
9883 // allocas or calls between the restore and the return, nuke the restore.
9884 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9885 return EraseInstFromFunction(CI);
9886 break;
9887 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009888 }
9889
Chris Lattner8b0ea312006-01-13 20:11:04 +00009890 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009891}
9892
9893// InvokeInst simplification
9894//
9895Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009896 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009897}
9898
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009899/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9900/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009901static bool isSafeToEliminateVarargsCast(const CallSite CS,
9902 const CastInst * const CI,
9903 const TargetData * const TD,
9904 const int ix) {
9905 if (!CI->isLosslessCast())
9906 return false;
9907
9908 // The size of ByVal arguments is derived from the type, so we
9909 // can't change to a type with a different size. If the size were
9910 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009911 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009912 return true;
9913
9914 const Type* SrcTy =
9915 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9916 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9917 if (!SrcTy->isSized() || !DstTy->isSized())
9918 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009919 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009920 return false;
9921 return true;
9922}
9923
Chris Lattnera44d8a22003-10-07 22:32:43 +00009924// visitCallSite - Improvements for call and invoke instructions.
9925//
9926Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009927 bool Changed = false;
9928
9929 // If the callee is a constexpr cast of a function, attempt to move the cast
9930 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009931 if (transformConstExprCastCall(CS)) return 0;
9932
Chris Lattner6c266db2003-10-07 22:54:13 +00009933 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009934
Chris Lattner08b22ec2005-05-13 07:09:09 +00009935 if (Function *CalleeF = dyn_cast<Function>(Callee))
9936 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9937 Instruction *OldCall = CS.getInstruction();
9938 // If the call and callee calling conventions don't match, this call must
9939 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009940 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009941 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +00009942 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009943 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009944 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009945 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9946 return EraseInstFromFunction(*OldCall);
9947 return 0;
9948 }
9949
Chris Lattner17be6352004-10-18 02:59:09 +00009950 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9951 // This instruction is not reachable, just remove it. We insert a store to
9952 // undef so that we know that this code is not reachable, despite the fact
9953 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009954 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +00009955 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +00009956 CS.getInstruction());
9957
9958 if (!CS.getInstruction()->use_empty())
9959 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009960 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009961
9962 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9963 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009964 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009965 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009966 }
Chris Lattner17be6352004-10-18 02:59:09 +00009967 return EraseInstFromFunction(*CS.getInstruction());
9968 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009969
Duncan Sandscdb6d922007-09-17 10:26:40 +00009970 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9971 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9972 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9973 return transformCallThroughTrampoline(CS);
9974
Chris Lattner6c266db2003-10-07 22:54:13 +00009975 const PointerType *PTy = cast<PointerType>(Callee->getType());
9976 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9977 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009978 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009979 // See if we can optimize any arguments passed through the varargs area of
9980 // the call.
9981 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009982 E = CS.arg_end(); I != E; ++I, ++ix) {
9983 CastInst *CI = dyn_cast<CastInst>(*I);
9984 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9985 *I = CI->getOperand(0);
9986 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009987 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009988 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009989 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009990
Duncan Sandsf0c33542007-12-19 21:13:37 +00009991 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009992 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009993 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009994 Changed = true;
9995 }
9996
Chris Lattner6c266db2003-10-07 22:54:13 +00009997 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009998}
9999
Chris Lattner9fe38862003-06-19 17:00:31 +000010000// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10001// attempt to move the cast to the arguments of the call/invoke.
10002//
10003bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10004 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10005 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010006 if (CE->getOpcode() != Instruction::BitCast ||
10007 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010008 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010009 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010010 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010011 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010012
10013 // Okay, this is a cast from a function to a different type. Unless doing so
10014 // would cause a type conversion of one of our arguments, change this call to
10015 // be a direct call with arguments casted to the appropriate types.
10016 //
10017 const FunctionType *FT = Callee->getFunctionType();
10018 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010019 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010020
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010021 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010022 return false; // TODO: Handle multiple return values.
10023
Chris Lattnerf78616b2004-01-14 06:06:08 +000010024 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010025 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010026 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010027 // Conversion is ok if changing from one pointer type to another or from
10028 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010029 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010030 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010031 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010032 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010033 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010034
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010035 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010036 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010037 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010038 return false; // Cannot transform this return value.
10039
Chris Lattner58d74912008-03-12 17:45:29 +000010040 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010041 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010042 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010043 return false; // Attribute not compatible with transformed value.
10044 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010045
Chris Lattnerf78616b2004-01-14 06:06:08 +000010046 // If the callsite is an invoke instruction, and the return value is used by
10047 // a PHI node in a successor, we cannot change the return type of the call
10048 // because there is no place to put the cast instruction (without breaking
10049 // the critical edge). Bail out in this case.
10050 if (!Caller->use_empty())
10051 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10052 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10053 UI != E; ++UI)
10054 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10055 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010056 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010057 return false;
10058 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010059
10060 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10061 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010062
Chris Lattner9fe38862003-06-19 17:00:31 +000010063 CallSite::arg_iterator AI = CS.arg_begin();
10064 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10065 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010066 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010067
10068 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010069 return false; // Cannot transform this parameter value.
10070
Devang Patel19c87462008-09-26 22:53:05 +000010071 if (CallerPAL.getParamAttributes(i + 1)
10072 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010073 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010074
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010075 // Converting from one pointer type to another or between a pointer and an
10076 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010077 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010078 (TD && ((isa<PointerType>(ParamTy) ||
10079 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10080 (isa<PointerType>(ActTy) ||
10081 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010082 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010083 }
10084
10085 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010086 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010087 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010088
Chris Lattner58d74912008-03-12 17:45:29 +000010089 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10090 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010091 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010092 // won't be dropping them. Check that these extra arguments have attributes
10093 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010094 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10095 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010096 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010097 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010098 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010099 return false;
10100 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010101
Chris Lattner9fe38862003-06-19 17:00:31 +000010102 // Okay, we decided that this is a safe thing to do: go ahead and start
10103 // inserting cast instructions as necessary...
10104 std::vector<Value*> Args;
10105 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010106 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010107 attrVec.reserve(NumCommonArgs);
10108
10109 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010110 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010111
10112 // If the return value is not being used, the type may not be compatible
10113 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010114 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010115
10116 // Add the new return attributes.
10117 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010118 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010119
10120 AI = CS.arg_begin();
10121 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10122 const Type *ParamTy = FT->getParamType(i);
10123 if ((*AI)->getType() == ParamTy) {
10124 Args.push_back(*AI);
10125 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010126 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010127 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010128 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010129 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010130
10131 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010132 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010133 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010134 }
10135
10136 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010137 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010138 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010139 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010140
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010141 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010142 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010144 errs() << "WARNING: While resolving call to function '"
10145 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010146 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010147 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010148 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10149 const Type *PTy = getPromotedType((*AI)->getType());
10150 if (PTy != (*AI)->getType()) {
10151 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010152 Instruction::CastOps opcode =
10153 CastInst::getCastOpcode(*AI, false, PTy, false);
10154 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010155 } else {
10156 Args.push_back(*AI);
10157 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010158
Duncan Sandse1e520f2008-01-13 08:02:44 +000010159 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010160 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010161 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010162 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010163 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010164 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010165
Devang Patel19c87462008-09-26 22:53:05 +000010166 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10167 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10168
Owen Anderson1d0be152009-08-13 21:58:54 +000010169 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010170 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010171
Eric Christophera66297a2009-07-25 02:45:27 +000010172 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10173 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010174
Chris Lattner9fe38862003-06-19 17:00:31 +000010175 Instruction *NC;
10176 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010177 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010178 Args.begin(), Args.end(),
10179 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010180 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010181 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010182 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010183 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10184 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010185 CallInst *CI = cast<CallInst>(Caller);
10186 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010187 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010188 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010189 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010190 }
10191
Chris Lattner6934a042007-02-11 01:23:03 +000010192 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010193 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010194 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010195 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010196 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010197 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010198 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010199
10200 // If this is an invoke instruction, we should insert it after the first
10201 // non-phi, instruction in the normal successor block.
10202 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010203 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010204 InsertNewInstBefore(NC, *I);
10205 } else {
10206 // Otherwise, it's a call, just insert cast right after the call instr
10207 InsertNewInstBefore(NC, *Caller);
10208 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010209 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010210 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010211 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010212 }
10213 }
10214
Chris Lattner931f8f32009-08-31 05:17:58 +000010215
10216 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010217 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010218
10219 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010220 return true;
10221}
10222
Duncan Sandscdb6d922007-09-17 10:26:40 +000010223// transformCallThroughTrampoline - Turn a call to a function created by the
10224// init_trampoline intrinsic into a direct call to the underlying function.
10225//
10226Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10227 Value *Callee = CS.getCalledValue();
10228 const PointerType *PTy = cast<PointerType>(Callee->getType());
10229 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010230 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010231
10232 // If the call already has the 'nest' attribute somewhere then give up -
10233 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010234 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010235 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010236
10237 IntrinsicInst *Tramp =
10238 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10239
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010240 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010241 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10242 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10243
Devang Patel05988662008-09-25 21:00:45 +000010244 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010245 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010246 unsigned NestIdx = 1;
10247 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010248 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010249
10250 // Look for a parameter marked with the 'nest' attribute.
10251 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10252 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010253 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010254 // Record the parameter type and any other attributes.
10255 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010256 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010257 break;
10258 }
10259
10260 if (NestTy) {
10261 Instruction *Caller = CS.getInstruction();
10262 std::vector<Value*> NewArgs;
10263 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10264
Devang Patel05988662008-09-25 21:00:45 +000010265 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010266 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010267
Duncan Sandscdb6d922007-09-17 10:26:40 +000010268 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010269 // mean appending it. Likewise for attributes.
10270
Devang Patel19c87462008-09-26 22:53:05 +000010271 // Add any result attributes.
10272 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010273 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010274
Duncan Sandscdb6d922007-09-17 10:26:40 +000010275 {
10276 unsigned Idx = 1;
10277 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10278 do {
10279 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010280 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010281 Value *NestVal = Tramp->getOperand(3);
10282 if (NestVal->getType() != NestTy)
10283 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10284 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010285 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010286 }
10287
10288 if (I == E)
10289 break;
10290
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010291 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010292 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010293 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010294 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010295 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010296
10297 ++Idx, ++I;
10298 } while (1);
10299 }
10300
Devang Patel19c87462008-09-26 22:53:05 +000010301 // Add any function attributes.
10302 if (Attributes Attr = Attrs.getFnAttributes())
10303 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10304
Duncan Sandscdb6d922007-09-17 10:26:40 +000010305 // The trampoline may have been bitcast to a bogus type (FTy).
10306 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010307 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010308
Duncan Sandscdb6d922007-09-17 10:26:40 +000010309 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010310 NewTypes.reserve(FTy->getNumParams()+1);
10311
Duncan Sandscdb6d922007-09-17 10:26:40 +000010312 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010313 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010314 {
10315 unsigned Idx = 1;
10316 FunctionType::param_iterator I = FTy->param_begin(),
10317 E = FTy->param_end();
10318
10319 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010320 if (Idx == NestIdx)
10321 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010322 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010323
10324 if (I == E)
10325 break;
10326
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010327 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010328 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010329
10330 ++Idx, ++I;
10331 } while (1);
10332 }
10333
10334 // Replace the trampoline call with a direct call. Let the generic
10335 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010336 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010337 FTy->isVarArg());
10338 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010339 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010340 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010341 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010342 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10343 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010344
10345 Instruction *NewCaller;
10346 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010347 NewCaller = InvokeInst::Create(NewCallee,
10348 II->getNormalDest(), II->getUnwindDest(),
10349 NewArgs.begin(), NewArgs.end(),
10350 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010351 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010352 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010354 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10355 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010356 if (cast<CallInst>(Caller)->isTailCall())
10357 cast<CallInst>(NewCaller)->setTailCall();
10358 cast<CallInst>(NewCaller)->
10359 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010360 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010361 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010362 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010363 Caller->replaceAllUsesWith(NewCaller);
10364 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010365 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366 return 0;
10367 }
10368 }
10369
10370 // Replace the trampoline call with a direct call. Since there is no 'nest'
10371 // parameter, there is no need to adjust the argument list. Let the generic
10372 // code sort out any function type mismatches.
10373 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010374 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010375 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 CS.setCalledFunction(NewCallee);
10377 return CS.getInstruction();
10378}
10379
Dan Gohman9ad29202009-09-16 16:50:24 +000010380/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10381/// 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 +000010382/// and a single binop.
10383Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10384 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010385 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010386 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010387 Value *LHSVal = FirstInst->getOperand(0);
10388 Value *RHSVal = FirstInst->getOperand(1);
10389
10390 const Type *LHSType = LHSVal->getType();
10391 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010392
Dan Gohman9ad29202009-09-16 16:50:24 +000010393 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010394 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010395 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010396 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010397 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010398 // types or GEP's with different index types.
10399 I->getOperand(0)->getType() != LHSType ||
10400 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010401 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010402
10403 // If they are CmpInst instructions, check their predicates
10404 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10405 if (cast<CmpInst>(I)->getPredicate() !=
10406 cast<CmpInst>(FirstInst)->getPredicate())
10407 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010408
10409 // Keep track of which operand needs a phi node.
10410 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10411 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010412 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010413
10414 // If both LHS and RHS would need a PHI, don't do this transformation,
10415 // because it would increase the number of PHIs entering the block,
10416 // which leads to higher register pressure. This is especially
10417 // bad when the PHIs are in the header of a loop.
10418 if (!LHSVal && !RHSVal)
10419 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010420
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010421 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010422
Chris Lattner7da52b22006-11-01 04:51:18 +000010423 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010424 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010425 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010426 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010427 NewLHS = PHINode::Create(LHSType,
10428 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010429 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10430 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010431 InsertNewInstBefore(NewLHS, PN);
10432 LHSVal = NewLHS;
10433 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010434
10435 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010436 NewRHS = PHINode::Create(RHSType,
10437 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010438 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10439 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010440 InsertNewInstBefore(NewRHS, PN);
10441 RHSVal = NewRHS;
10442 }
10443
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010444 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010445 if (NewLHS || NewRHS) {
10446 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10447 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10448 if (NewLHS) {
10449 Value *NewInLHS = InInst->getOperand(0);
10450 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10451 }
10452 if (NewRHS) {
10453 Value *NewInRHS = InInst->getOperand(1);
10454 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10455 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010456 }
10457 }
10458
Chris Lattner7da52b22006-11-01 04:51:18 +000010459 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010460 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010461 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010462 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010463 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010464}
10465
Chris Lattner05f18922008-12-01 02:34:36 +000010466Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10467 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10468
10469 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10470 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010471 // This is true if all GEP bases are allocas and if all indices into them are
10472 // constants.
10473 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010474
10475 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010476 // more than one phi, which leads to higher register pressure. This is
10477 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010478 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010479
Dan Gohman9ad29202009-09-16 16:50:24 +000010480 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010481 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10482 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10483 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10484 GEP->getNumOperands() != FirstInst->getNumOperands())
10485 return 0;
10486
Chris Lattner36d3e322009-02-21 00:46:50 +000010487 // Keep track of whether or not all GEPs are of alloca pointers.
10488 if (AllBasePointersAreAllocas &&
10489 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10490 !GEP->hasAllConstantIndices()))
10491 AllBasePointersAreAllocas = false;
10492
Chris Lattner05f18922008-12-01 02:34:36 +000010493 // Compare the operand lists.
10494 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10495 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10496 continue;
10497
10498 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10499 // if one of the PHIs has a constant for the index. The index may be
10500 // substantially cheaper to compute for the constants, so making it a
10501 // variable index could pessimize the path. This also handles the case
10502 // for struct indices, which must always be constant.
10503 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10504 isa<ConstantInt>(GEP->getOperand(op)))
10505 return 0;
10506
10507 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10508 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010509
10510 // If we already needed a PHI for an earlier operand, and another operand
10511 // also requires a PHI, we'd be introducing more PHIs than we're
10512 // eliminating, which increases register pressure on entry to the PHI's
10513 // block.
10514 if (NeededPhi)
10515 return 0;
10516
Chris Lattner05f18922008-12-01 02:34:36 +000010517 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010518 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010519 }
10520 }
10521
Chris Lattner36d3e322009-02-21 00:46:50 +000010522 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010523 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010524 // offset calculation, but all the predecessors will have to materialize the
10525 // stack address into a register anyway. We'd actually rather *clone* the
10526 // load up into the predecessors so that we have a load of a gep of an alloca,
10527 // which can usually all be folded into the load.
10528 if (AllBasePointersAreAllocas)
10529 return 0;
10530
Chris Lattner05f18922008-12-01 02:34:36 +000010531 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10532 // that is variable.
10533 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10534
10535 bool HasAnyPHIs = false;
10536 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10537 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10538 Value *FirstOp = FirstInst->getOperand(i);
10539 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10540 FirstOp->getName()+".pn");
10541 InsertNewInstBefore(NewPN, PN);
10542
10543 NewPN->reserveOperandSpace(e);
10544 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10545 OperandPhis[i] = NewPN;
10546 FixedOperands[i] = NewPN;
10547 HasAnyPHIs = true;
10548 }
10549
10550
10551 // Add all operands to the new PHIs.
10552 if (HasAnyPHIs) {
10553 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10554 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10555 BasicBlock *InBB = PN.getIncomingBlock(i);
10556
10557 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10558 if (PHINode *OpPhi = OperandPhis[op])
10559 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10560 }
10561 }
10562
10563 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010564 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10565 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10566 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010567 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10568 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010569}
10570
10571
Chris Lattner21550882009-02-23 05:56:17 +000010572/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10573/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010574/// obvious the value of the load is not changed from the point of the load to
10575/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010576///
10577/// Finally, it is safe, but not profitable, to sink a load targetting a
10578/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10579/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010580static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010581 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10582
10583 for (++BBI; BBI != E; ++BBI)
10584 if (BBI->mayWriteToMemory())
10585 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010586
10587 // Check for non-address taken alloca. If not address-taken already, it isn't
10588 // profitable to do this xform.
10589 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10590 bool isAddressTaken = false;
10591 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10592 UI != E; ++UI) {
10593 if (isa<LoadInst>(UI)) continue;
10594 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10595 // If storing TO the alloca, then the address isn't taken.
10596 if (SI->getOperand(1) == AI) continue;
10597 }
10598 isAddressTaken = true;
10599 break;
10600 }
10601
Chris Lattner36d3e322009-02-21 00:46:50 +000010602 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010603 return false;
10604 }
10605
Chris Lattner36d3e322009-02-21 00:46:50 +000010606 // If this load is a load from a GEP with a constant offset from an alloca,
10607 // then we don't want to sink it. In its present form, it will be
10608 // load [constant stack offset]. Sinking it will cause us to have to
10609 // materialize the stack addresses in each predecessor in a register only to
10610 // do a shared load from register in the successor.
10611 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10612 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10613 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10614 return false;
10615
Chris Lattner76c73142006-11-01 07:13:54 +000010616 return true;
10617}
10618
Chris Lattner9fe38862003-06-19 17:00:31 +000010619
Chris Lattnerbac32862004-11-14 19:13:23 +000010620// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10621// operator and they all are only used by the PHI, PHI together their
10622// inputs, and do the operation once, to the result of the PHI.
10623Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10624 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10625
10626 // Scan the instruction, looking for input operations that can be folded away.
10627 // If all input operands to the phi are the same instruction (e.g. a cast from
10628 // the same type or "+42") we can pull the operation through the PHI, reducing
10629 // code size and simplifying code.
10630 Constant *ConstantOp = 0;
10631 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010632 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010633 if (isa<CastInst>(FirstInst)) {
10634 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010635 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010636 // Can fold binop, compare or shift here if the RHS is a constant,
10637 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010638 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010639 if (ConstantOp == 0)
10640 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010641 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10642 isVolatile = LI->isVolatile();
10643 // We can't sink the load if the loaded value could be modified between the
10644 // load and the PHI.
10645 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010646 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010647 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010648
10649 // If the PHI is of volatile loads and the load block has multiple
10650 // successors, sinking it would remove a load of the volatile value from
10651 // the path through the other successor.
10652 if (isVolatile &&
10653 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10654 return 0;
10655
Chris Lattner9c080502006-11-01 07:43:41 +000010656 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010657 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010658 } else {
10659 return 0; // Cannot fold this operation.
10660 }
10661
10662 // Check to see if all arguments are the same operation.
10663 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10664 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10665 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010666 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010667 return 0;
10668 if (CastSrcTy) {
10669 if (I->getOperand(0)->getType() != CastSrcTy)
10670 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010671 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010672 // We can't sink the load if the loaded value could be modified between
10673 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010674 if (LI->isVolatile() != isVolatile ||
10675 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010676 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010677 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010678
Chris Lattner71042962008-07-08 17:18:32 +000010679 // If the PHI is of volatile loads and the load block has multiple
10680 // successors, sinking it would remove a load of the volatile value from
10681 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010682 if (isVolatile &&
10683 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10684 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010685
Chris Lattnerbac32862004-11-14 19:13:23 +000010686 } else if (I->getOperand(1) != ConstantOp) {
10687 return 0;
10688 }
10689 }
10690
10691 // Okay, they are all the same operation. Create a new PHI node of the
10692 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010693 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10694 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010695 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010696
10697 Value *InVal = FirstInst->getOperand(0);
10698 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010699
10700 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010701 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10702 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10703 if (NewInVal != InVal)
10704 InVal = 0;
10705 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10706 }
10707
10708 Value *PhiVal;
10709 if (InVal) {
10710 // The new PHI unions all of the same values together. This is really
10711 // common, so we handle it intelligently here for compile-time speed.
10712 PhiVal = InVal;
10713 delete NewPN;
10714 } else {
10715 InsertNewInstBefore(NewPN, PN);
10716 PhiVal = NewPN;
10717 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010718
Chris Lattnerbac32862004-11-14 19:13:23 +000010719 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010720 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010721 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010722 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010723 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010724 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010725 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010726 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010727 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10728
10729 // If this was a volatile load that we are merging, make sure to loop through
10730 // and mark all the input loads as non-volatile. If we don't do this, we will
10731 // insert a new volatile load and the old ones will not be deletable.
10732 if (isVolatile)
10733 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10734 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10735
10736 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010737}
Chris Lattnera1be5662002-05-02 17:06:02 +000010738
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010739/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10740/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010741static bool DeadPHICycle(PHINode *PN,
10742 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010743 if (PN->use_empty()) return true;
10744 if (!PN->hasOneUse()) return false;
10745
10746 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010747 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010748 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010749
10750 // Don't scan crazily complex things.
10751 if (PotentiallyDeadPHIs.size() == 16)
10752 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010753
10754 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10755 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010756
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010757 return false;
10758}
10759
Chris Lattnercf5008a2007-11-06 21:52:06 +000010760/// PHIsEqualValue - Return true if this phi node is always equal to
10761/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10762/// z = some value; x = phi (y, z); y = phi (x, z)
10763static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10764 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10765 // See if we already saw this PHI node.
10766 if (!ValueEqualPHIs.insert(PN))
10767 return true;
10768
10769 // Don't scan crazily complex things.
10770 if (ValueEqualPHIs.size() == 16)
10771 return false;
10772
10773 // Scan the operands to see if they are either phi nodes or are equal to
10774 // the value.
10775 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10776 Value *Op = PN->getIncomingValue(i);
10777 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10778 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10779 return false;
10780 } else if (Op != NonPhiInVal)
10781 return false;
10782 }
10783
10784 return true;
10785}
10786
10787
Chris Lattner473945d2002-05-06 18:06:38 +000010788// PHINode simplification
10789//
Chris Lattner7e708292002-06-25 16:13:24 +000010790Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010791 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010792 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010793
Owen Anderson7e057142006-07-10 22:03:18 +000010794 if (Value *V = PN.hasConstantValue())
10795 return ReplaceInstUsesWith(PN, V);
10796
Owen Anderson7e057142006-07-10 22:03:18 +000010797 // If all PHI operands are the same operation, pull them through the PHI,
10798 // reducing code size.
10799 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010800 isa<Instruction>(PN.getIncomingValue(1)) &&
10801 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10802 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10803 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10804 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010805 PN.getIncomingValue(0)->hasOneUse())
10806 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10807 return Result;
10808
10809 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10810 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10811 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010812 if (PN.hasOneUse()) {
10813 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10814 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010815 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010816 PotentiallyDeadPHIs.insert(&PN);
10817 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010818 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010819 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010820
10821 // If this phi has a single use, and if that use just computes a value for
10822 // the next iteration of a loop, delete the phi. This occurs with unused
10823 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10824 // common case here is good because the only other things that catch this
10825 // are induction variable analysis (sometimes) and ADCE, which is only run
10826 // late.
10827 if (PHIUser->hasOneUse() &&
10828 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10829 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010830 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010831 }
10832 }
Owen Anderson7e057142006-07-10 22:03:18 +000010833
Chris Lattnercf5008a2007-11-06 21:52:06 +000010834 // We sometimes end up with phi cycles that non-obviously end up being the
10835 // same value, for example:
10836 // z = some value; x = phi (y, z); y = phi (x, z)
10837 // where the phi nodes don't necessarily need to be in the same block. Do a
10838 // quick check to see if the PHI node only contains a single non-phi value, if
10839 // so, scan to see if the phi cycle is actually equal to that value.
10840 {
10841 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10842 // Scan for the first non-phi operand.
10843 while (InValNo != NumOperandVals &&
10844 isa<PHINode>(PN.getIncomingValue(InValNo)))
10845 ++InValNo;
10846
10847 if (InValNo != NumOperandVals) {
10848 Value *NonPhiInVal = PN.getOperand(InValNo);
10849
10850 // Scan the rest of the operands to see if there are any conflicts, if so
10851 // there is no need to recursively scan other phis.
10852 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10853 Value *OpVal = PN.getIncomingValue(InValNo);
10854 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10855 break;
10856 }
10857
10858 // If we scanned over all operands, then we have one unique value plus
10859 // phi values. Scan PHI nodes to see if they all merge in each other or
10860 // the value.
10861 if (InValNo == NumOperandVals) {
10862 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10863 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10864 return ReplaceInstUsesWith(PN, NonPhiInVal);
10865 }
10866 }
10867 }
Chris Lattner60921c92003-12-19 05:58:40 +000010868 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010869}
10870
Chris Lattner7e708292002-06-25 16:13:24 +000010871Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010872 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010873 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010874 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010875 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010876
Chris Lattnere87597f2004-10-16 18:11:37 +000010877 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010878 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010879
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010880 bool HasZeroPointerIndex = false;
10881 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10882 HasZeroPointerIndex = C->isNullValue();
10883
10884 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010885 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010886
Chris Lattner28977af2004-04-05 01:30:19 +000010887 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010888 if (TD) {
10889 bool MadeChange = false;
10890 unsigned PtrSize = TD->getPointerSizeInBits();
10891
10892 gep_type_iterator GTI = gep_type_begin(GEP);
10893 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10894 I != E; ++I, ++GTI) {
10895 if (!isa<SequentialType>(*GTI)) continue;
10896
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010897 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010898 // to what we need. If narrower, sign-extend it to what we need. This
10899 // explicit cast can make subsequent optimizations more obvious.
10900 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010901 if (OpBits == PtrSize)
10902 continue;
10903
Chris Lattner2345d1d2009-08-30 20:01:10 +000010904 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010905 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010906 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010907 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010908 }
Chris Lattner28977af2004-04-05 01:30:19 +000010909
Chris Lattner90ac28c2002-08-02 19:29:35 +000010910 // Combine Indices - If the source pointer to this getelementptr instruction
10911 // is a getelementptr instruction, combine the indices of the two
10912 // getelementptr instructions into a single instruction.
10913 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010914 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010915 // Note that if our source is a gep chain itself that we wait for that
10916 // chain to be resolved before we perform this transformation. This
10917 // avoids us creating a TON of code in some cases.
10918 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010919 if (GetElementPtrInst *SrcGEP =
10920 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10921 if (SrcGEP->getNumOperands() == 2)
10922 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010923
Chris Lattner72588fc2007-02-15 22:48:32 +000010924 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010925
10926 // Find out whether the last index in the source GEP is a sequential idx.
10927 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010928 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10929 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010930 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010931
Chris Lattner90ac28c2002-08-02 19:29:35 +000010932 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010933 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010934 // Replace: gep (gep %P, long B), long A, ...
10935 // With: T = long A+B; gep %P, T, ...
10936 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010937 Value *Sum;
10938 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10939 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010940 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010941 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010942 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010943 Sum = SO1;
10944 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010945 // If they aren't the same type, then the input hasn't been processed
10946 // by the loop above yet (which canonicalizes sequential index types to
10947 // intptr_t). Just avoid transforming this until the input has been
10948 // normalized.
10949 if (SO1->getType() != GO1->getType())
10950 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010951 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010952 }
Chris Lattner620ce142004-05-07 22:09:22 +000010953
Chris Lattnerab984842009-08-30 05:30:55 +000010954 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010955 if (Src->getNumOperands() == 2) {
10956 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010957 GEP.setOperand(1, Sum);
10958 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010959 }
Chris Lattnerab984842009-08-30 05:30:55 +000010960 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010961 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010962 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010963 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010964 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010965 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010966 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010967 Indices.append(Src->op_begin()+1, Src->op_end());
10968 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010969 }
10970
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010971 if (!Indices.empty())
10972 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10973 Src->isInBounds()) ?
10974 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10975 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010976 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010977 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010978 }
10979
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010980 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10981 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010982 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010983
Chris Lattner2de23192009-08-30 20:38:21 +000010984 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10985 // want to change the gep until the bitcasts are eliminated.
10986 if (getBitCastOperand(X)) {
10987 Worklist.AddValue(PtrOp);
10988 return 0;
10989 }
10990
Chris Lattner963f4ba2009-08-30 20:36:46 +000010991 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10992 // into : GEP [10 x i8]* X, i32 0, ...
10993 //
10994 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10995 // into : GEP i8* X, ...
10996 //
10997 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000010998 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000010999 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11000 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011001 if (const ArrayType *CATy =
11002 dyn_cast<ArrayType>(CPTy->getElementType())) {
11003 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11004 if (CATy->getElementType() == XTy->getElementType()) {
11005 // -> GEP i8* X, ...
11006 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011007 return cast<GEPOperator>(&GEP)->isInBounds() ?
11008 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11009 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011010 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11011 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011012 }
11013
11014 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011015 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011016 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011017 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011018 // At this point, we know that the cast source type is a pointer
11019 // to an array of the same type as the destination pointer
11020 // array. Because the array type is never stepped over (there
11021 // is a leading zero) we can fold the cast into this GEP.
11022 GEP.setOperand(0, X);
11023 return &GEP;
11024 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011025 }
11026 }
Chris Lattnereed48272005-09-13 00:40:14 +000011027 } else if (GEP.getNumOperands() == 2) {
11028 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011029 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11030 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011031 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11032 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011033 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011034 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11035 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011036 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011037 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011038 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011039 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11040 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011041 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011042 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011043 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011044 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011045
11046 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011047 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011048 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011049 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011050
Owen Anderson1d0be152009-08-13 21:58:54 +000011051 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011052 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011053 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011054
11055 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11056 // allow either a mul, shift, or constant here.
11057 Value *NewIdx = 0;
11058 ConstantInt *Scale = 0;
11059 if (ArrayEltSize == 1) {
11060 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011061 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011062 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011063 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011064 Scale = CI;
11065 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11066 if (Inst->getOpcode() == Instruction::Shl &&
11067 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011068 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11069 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011070 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011071 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011072 NewIdx = Inst->getOperand(0);
11073 } else if (Inst->getOpcode() == Instruction::Mul &&
11074 isa<ConstantInt>(Inst->getOperand(1))) {
11075 Scale = cast<ConstantInt>(Inst->getOperand(1));
11076 NewIdx = Inst->getOperand(0);
11077 }
11078 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011079
Chris Lattner7835cdd2005-09-13 18:36:04 +000011080 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011081 // out, perform the transformation. Note, we don't know whether Scale is
11082 // signed or not. We'll use unsigned version of division/modulo
11083 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011084 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011085 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011086 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011087 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011088 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011089 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11090 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011091 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011092 }
11093
11094 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011095 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011096 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011097 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011098 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11099 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11100 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011101 // The NewGEP must be pointer typed, so must the old one -> BitCast
11102 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011103 }
11104 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011105 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011106 }
Chris Lattner58407792009-01-09 04:53:57 +000011107
Chris Lattner46cd5a12009-01-09 05:44:56 +000011108 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011109 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011110 /// Y = gep X, <...constant indices...>
11111 /// into a gep of the original struct. This is important for SROA and alias
11112 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011113 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011114 if (TD &&
11115 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011116 // Determine how much the GEP moves the pointer. We are guaranteed to get
11117 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011118 ConstantInt *OffsetV =
11119 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011120 int64_t Offset = OffsetV->getSExtValue();
11121
11122 // If this GEP instruction doesn't move the pointer, just replace the GEP
11123 // with a bitcast of the real input to the dest type.
11124 if (Offset == 0) {
11125 // If the bitcast is of an allocation, and the allocation will be
11126 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011127 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11128 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011129 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11130 if (Instruction *I = visitBitCast(*BCI)) {
11131 if (I != BCI) {
11132 I->takeName(BCI);
11133 BCI->getParent()->getInstList().insert(BCI, I);
11134 ReplaceInstUsesWith(*BCI, I);
11135 }
11136 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011137 }
Chris Lattner58407792009-01-09 04:53:57 +000011138 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011139 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011140 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011141
11142 // Otherwise, if the offset is non-zero, we need to find out if there is a
11143 // field at Offset in 'A's type. If so, we can pull the cast through the
11144 // GEP.
11145 SmallVector<Value*, 8> NewIndices;
11146 const Type *InTy =
11147 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011148 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011149 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11150 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11151 NewIndices.end()) :
11152 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11153 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011154
11155 if (NGEP->getType() == GEP.getType())
11156 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011157 NGEP->takeName(&GEP);
11158 return new BitCastInst(NGEP, GEP.getType());
11159 }
Chris Lattner58407792009-01-09 04:53:57 +000011160 }
11161 }
11162
Chris Lattner8a2a3112001-12-14 16:52:21 +000011163 return 0;
11164}
11165
Chris Lattner0864acf2002-11-04 16:18:53 +000011166Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11167 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011168 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011169 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11170 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011171 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011172 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011173
11174 // Create and insert the replacement instruction...
11175 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011176 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011177 else {
11178 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011179 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011180 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011181 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011182
Chris Lattner0864acf2002-11-04 16:18:53 +000011183 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011184 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011185 //
11186 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011187 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011188
11189 // Now that I is pointing to the first non-allocation-inst in the block,
11190 // insert our getelementptr instruction...
11191 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011192 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011193 Value *Idx[2];
11194 Idx[0] = NullIdx;
11195 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011196 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11197 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011198
11199 // Now make everything use the getelementptr instead of the original
11200 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011201 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011202 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011203 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011204 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011205 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011206
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011207 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011208 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011209 // Note that we only do this for alloca's, because malloc should allocate
11210 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011211 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011212 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011213
11214 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11215 if (AI.getAlignment() == 0)
11216 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11217 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011218
Chris Lattner0864acf2002-11-04 16:18:53 +000011219 return 0;
11220}
11221
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011222Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11223 Value *Op = FI.getOperand(0);
11224
Chris Lattner17be6352004-10-18 02:59:09 +000011225 // free undef -> unreachable.
11226 if (isa<UndefValue>(Op)) {
11227 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011228 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000011229 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011230 return EraseInstFromFunction(FI);
11231 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011232
Chris Lattner6160e852004-02-28 04:57:37 +000011233 // If we have 'free null' delete the instruction. This can happen in stl code
11234 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011235 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011236 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011237
11238 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11239 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11240 FI.setOperand(0, CI->getOperand(0));
11241 return &FI;
11242 }
11243
11244 // Change free (gep X, 0,0,0,0) into free(X)
11245 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11246 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011247 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011248 FI.setOperand(0, GEPI->getOperand(0));
11249 return &FI;
11250 }
11251 }
11252
11253 // Change free(malloc) into nothing, if the malloc has a single use.
11254 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11255 if (MI->hasOneUse()) {
11256 EraseInstFromFunction(FI);
11257 return EraseInstFromFunction(*MI);
11258 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011259 if (isMalloc(Op)) {
11260 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11261 if (Op->hasOneUse() && CI->hasOneUse()) {
11262 EraseInstFromFunction(FI);
11263 EraseInstFromFunction(*CI);
11264 return EraseInstFromFunction(*cast<Instruction>(Op));
11265 }
11266 } else {
11267 // Op is a call to malloc
11268 if (Op->hasOneUse()) {
11269 EraseInstFromFunction(FI);
11270 return EraseInstFromFunction(*cast<Instruction>(Op));
11271 }
11272 }
11273 }
Chris Lattner6160e852004-02-28 04:57:37 +000011274
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011275 return 0;
11276}
11277
11278
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011279/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011280static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011281 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011282 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011283 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011284 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011285
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011286 if (TD) {
11287 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11288 // Instead of loading constant c string, use corresponding integer value
11289 // directly if string length is small enough.
11290 std::string Str;
11291 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11292 unsigned len = Str.length();
11293 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11294 unsigned numBits = Ty->getPrimitiveSizeInBits();
11295 // Replace LI with immediate integer store.
11296 if ((numBits >> 3) == len + 1) {
11297 APInt StrVal(numBits, 0);
11298 APInt SingleChar(numBits, 0);
11299 if (TD->isLittleEndian()) {
11300 for (signed i = len-1; i >= 0; i--) {
11301 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11302 StrVal = (StrVal << 8) | SingleChar;
11303 }
11304 } else {
11305 for (unsigned i = 0; i < len; i++) {
11306 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11307 StrVal = (StrVal << 8) | SingleChar;
11308 }
11309 // Append NULL at the end.
11310 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011311 StrVal = (StrVal << 8) | SingleChar;
11312 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011313 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011314 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011315 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011316 }
11317 }
11318 }
11319
Mon P Wang6753f952009-02-07 22:19:29 +000011320 const PointerType *DestTy = cast<PointerType>(CI->getType());
11321 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011322 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011323
11324 // If the address spaces don't match, don't eliminate the cast.
11325 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11326 return 0;
11327
Chris Lattnerb89e0712004-07-13 01:49:43 +000011328 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011329
Reid Spencer42230162007-01-22 05:51:25 +000011330 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011331 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011332 // If the source is an array, the code below will not succeed. Check to
11333 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11334 // constants.
11335 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11336 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11337 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011338 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011339 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011340 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011341 SrcTy = cast<PointerType>(CastOp->getType());
11342 SrcPTy = SrcTy->getElementType();
11343 }
11344
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011345 if (IC.getTargetData() &&
11346 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011347 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011348 // Do not allow turning this into a load of an integer, which is then
11349 // casted to a pointer, this pessimizes pointer analysis a lot.
11350 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011351 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11352 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011353
Chris Lattnerf9527852005-01-31 04:50:46 +000011354 // Okay, we are casting from one integer or pointer type to another of
11355 // the same size. Instead of casting the pointer before the load, cast
11356 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011357 Value *NewLoad =
11358 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011359 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011360 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011361 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011362 }
11363 }
11364 return 0;
11365}
11366
Chris Lattner833b8a42003-06-26 05:06:25 +000011367Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11368 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011369
Dan Gohman9941f742007-07-20 16:34:21 +000011370 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011371 if (TD) {
11372 unsigned KnownAlign =
11373 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11374 if (KnownAlign >
11375 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11376 LI.getAlignment()))
11377 LI.setAlignment(KnownAlign);
11378 }
Dan Gohman9941f742007-07-20 16:34:21 +000011379
Chris Lattner963f4ba2009-08-30 20:36:46 +000011380 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011381 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011382 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011383 return Res;
11384
11385 // None of the following transforms are legal for volatile loads.
11386 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011387
Dan Gohman2276a7b2008-10-15 23:19:35 +000011388 // Do really simple store-to-load forwarding and load CSE, to catch cases
11389 // where there are several consequtive memory accesses to the same location,
11390 // separated by a few arithmetic operations.
11391 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011392 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11393 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011394
Christopher Lambb15147e2007-12-29 07:56:53 +000011395 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11396 const Value *GEPI0 = GEPI->getOperand(0);
11397 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011398 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011399 // Insert a new store to null instruction before the load to indicate
11400 // that this code is not reachable. We do this instead of inserting
11401 // an unreachable instruction directly because we cannot modify the
11402 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011403 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011404 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011405 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011406 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011407 }
Chris Lattner37366c12005-05-01 04:24:53 +000011408
Chris Lattnere87597f2004-10-16 18:11:37 +000011409 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011410 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011411 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011412 if (isa<UndefValue>(C) ||
11413 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011414 // Insert a new store to null instruction before the load to indicate that
11415 // this code is not reachable. We do this instead of inserting an
11416 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011417 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011418 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011419 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011420 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011421
Chris Lattnere87597f2004-10-16 18:11:37 +000011422 // Instcombine load (constant global) into the value loaded.
11423 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011424 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011425 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011426
Chris Lattnere87597f2004-10-16 18:11:37 +000011427 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011428 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011429 if (CE->getOpcode() == Instruction::GetElementPtr) {
11430 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011431 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011432 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +000011433 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011434 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011435 if (CE->getOperand(0)->isNullValue()) {
11436 // Insert a new store to null instruction before the load to indicate
11437 // that this code is not reachable. We do this instead of inserting
11438 // an unreachable instruction directly because we cannot modify the
11439 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011440 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011441 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011442 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011443 }
11444
Reid Spencer3da59db2006-11-27 01:05:10 +000011445 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011446 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011447 return Res;
11448 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011449 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011450 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011451
11452 // If this load comes from anywhere in a constant global, and if the global
11453 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011454 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011455 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011456 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011457 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011458 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011459 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011460 }
11461 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011462
Chris Lattner37366c12005-05-01 04:24:53 +000011463 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011464 // Change select and PHI nodes to select values instead of addresses: this
11465 // helps alias analysis out a lot, allows many others simplifications, and
11466 // exposes redundancy in the code.
11467 //
11468 // Note that we cannot do the transformation unless we know that the
11469 // introduced loads cannot trap! Something like this is valid as long as
11470 // the condition is always false: load (select bool %C, int* null, int* %G),
11471 // but it would not be valid if we transformed it to load from null
11472 // unconditionally.
11473 //
11474 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11475 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011476 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11477 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011478 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11479 SI->getOperand(1)->getName()+".val");
11480 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11481 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011482 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011483 }
11484
Chris Lattner684fe212004-09-23 15:46:00 +000011485 // load (select (cond, null, P)) -> load P
11486 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11487 if (C->isNullValue()) {
11488 LI.setOperand(0, SI->getOperand(2));
11489 return &LI;
11490 }
11491
11492 // load (select (cond, P, null)) -> load P
11493 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11494 if (C->isNullValue()) {
11495 LI.setOperand(0, SI->getOperand(1));
11496 return &LI;
11497 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011498 }
11499 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011500 return 0;
11501}
11502
Reid Spencer55af2b52007-01-19 21:20:31 +000011503/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011504/// when possible. This makes it generally easy to do alias analysis and/or
11505/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011506static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11507 User *CI = cast<User>(SI.getOperand(1));
11508 Value *CastOp = CI->getOperand(0);
11509
11510 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011511 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11512 if (SrcTy == 0) return 0;
11513
11514 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011515
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011516 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11517 return 0;
11518
Chris Lattner3914f722009-01-24 01:00:13 +000011519 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11520 /// to its first element. This allows us to handle things like:
11521 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11522 /// on 32-bit hosts.
11523 SmallVector<Value*, 4> NewGEPIndices;
11524
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011525 // If the source is an array, the code below will not succeed. Check to
11526 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11527 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011528 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11529 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011530 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011531 NewGEPIndices.push_back(Zero);
11532
11533 while (1) {
11534 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011535 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011536 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011537 NewGEPIndices.push_back(Zero);
11538 SrcPTy = STy->getElementType(0);
11539 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11540 NewGEPIndices.push_back(Zero);
11541 SrcPTy = ATy->getElementType();
11542 } else {
11543 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011544 }
Chris Lattner3914f722009-01-24 01:00:13 +000011545 }
11546
Owen Andersondebcb012009-07-29 22:17:13 +000011547 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011548 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011549
11550 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11551 return 0;
11552
Chris Lattner71759c42009-01-16 20:12:52 +000011553 // If the pointers point into different address spaces or if they point to
11554 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011555 if (!IC.getTargetData() ||
11556 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011557 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011558 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11559 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011560 return 0;
11561
11562 // Okay, we are casting from one integer or pointer type to another of
11563 // the same size. Instead of casting the pointer before
11564 // the store, cast the value to be stored.
11565 Value *NewCast;
11566 Value *SIOp0 = SI.getOperand(0);
11567 Instruction::CastOps opcode = Instruction::BitCast;
11568 const Type* CastSrcTy = SIOp0->getType();
11569 const Type* CastDstTy = SrcPTy;
11570 if (isa<PointerType>(CastDstTy)) {
11571 if (CastSrcTy->isInteger())
11572 opcode = Instruction::IntToPtr;
11573 } else if (isa<IntegerType>(CastDstTy)) {
11574 if (isa<PointerType>(SIOp0->getType()))
11575 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011576 }
Chris Lattner3914f722009-01-24 01:00:13 +000011577
11578 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11579 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011580 if (!NewGEPIndices.empty())
11581 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11582 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011583
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011584 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11585 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011586 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011587}
11588
Chris Lattner4aebaee2008-11-27 08:56:30 +000011589/// equivalentAddressValues - Test if A and B will obviously have the same
11590/// value. This includes recognizing that %t0 and %t1 will have the same
11591/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011592/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011593/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011594/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011595/// %t2 = load i32* %t1
11596///
11597static bool equivalentAddressValues(Value *A, Value *B) {
11598 // Test if the values are trivially equivalent.
11599 if (A == B) return true;
11600
11601 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011602 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11603 // its only used to compare two uses within the same basic block, which
11604 // means that they'll always either have the same value or one of them
11605 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011606 if (isa<BinaryOperator>(A) ||
11607 isa<CastInst>(A) ||
11608 isa<PHINode>(A) ||
11609 isa<GetElementPtrInst>(A))
11610 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011611 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011612 return true;
11613
11614 // Otherwise they may not be equivalent.
11615 return false;
11616}
11617
Dale Johannesen4945c652009-03-03 21:26:39 +000011618// If this instruction has two uses, one of which is a llvm.dbg.declare,
11619// return the llvm.dbg.declare.
11620DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11621 if (!V->hasNUses(2))
11622 return 0;
11623 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11624 UI != E; ++UI) {
11625 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11626 return DI;
11627 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11628 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11629 return DI;
11630 }
11631 }
11632 return 0;
11633}
11634
Chris Lattner2f503e62005-01-31 05:36:43 +000011635Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11636 Value *Val = SI.getOperand(0);
11637 Value *Ptr = SI.getOperand(1);
11638
11639 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011640 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011641 ++NumCombined;
11642 return 0;
11643 }
Chris Lattner836692d2007-01-15 06:51:56 +000011644
11645 // If the RHS is an alloca with a single use, zapify the store, making the
11646 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011647 // If the RHS is an alloca with a two uses, the other one being a
11648 // llvm.dbg.declare, zapify the store and the declare, making the
11649 // alloca dead. We must do this to prevent declare's from affecting
11650 // codegen.
11651 if (!SI.isVolatile()) {
11652 if (Ptr->hasOneUse()) {
11653 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011654 EraseInstFromFunction(SI);
11655 ++NumCombined;
11656 return 0;
11657 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011658 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11659 if (isa<AllocaInst>(GEP->getOperand(0))) {
11660 if (GEP->getOperand(0)->hasOneUse()) {
11661 EraseInstFromFunction(SI);
11662 ++NumCombined;
11663 return 0;
11664 }
11665 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11666 EraseInstFromFunction(*DI);
11667 EraseInstFromFunction(SI);
11668 ++NumCombined;
11669 return 0;
11670 }
11671 }
11672 }
11673 }
11674 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11675 EraseInstFromFunction(*DI);
11676 EraseInstFromFunction(SI);
11677 ++NumCombined;
11678 return 0;
11679 }
Chris Lattner836692d2007-01-15 06:51:56 +000011680 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011681
Dan Gohman9941f742007-07-20 16:34:21 +000011682 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011683 if (TD) {
11684 unsigned KnownAlign =
11685 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11686 if (KnownAlign >
11687 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11688 SI.getAlignment()))
11689 SI.setAlignment(KnownAlign);
11690 }
Dan Gohman9941f742007-07-20 16:34:21 +000011691
Dale Johannesenacb51a32009-03-03 01:43:03 +000011692 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011693 // stores to the same location, separated by a few arithmetic operations. This
11694 // situation often occurs with bitfield accesses.
11695 BasicBlock::iterator BBI = &SI;
11696 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11697 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011698 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011699 // Don't count debug info directives, lest they affect codegen,
11700 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11701 // It is necessary for correctness to skip those that feed into a
11702 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011703 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011704 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011705 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011706 continue;
11707 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011708
11709 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11710 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011711 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11712 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011713 ++NumDeadStore;
11714 ++BBI;
11715 EraseInstFromFunction(*PrevSI);
11716 continue;
11717 }
11718 break;
11719 }
11720
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011721 // If this is a load, we have to stop. However, if the loaded value is from
11722 // the pointer we're loading and is producing the pointer we're storing,
11723 // then *this* store is dead (X = load P; store X -> P).
11724 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011725 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11726 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011727 EraseInstFromFunction(SI);
11728 ++NumCombined;
11729 return 0;
11730 }
11731 // Otherwise, this is a load from some other location. Stores before it
11732 // may not be dead.
11733 break;
11734 }
11735
Chris Lattner9ca96412006-02-08 03:25:32 +000011736 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011737 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011738 break;
11739 }
11740
11741
11742 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011743
11744 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011745 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011746 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011747 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011748 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011749 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011750 ++NumCombined;
11751 }
11752 return 0; // Do not modify these!
11753 }
11754
11755 // store undef, Ptr -> noop
11756 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011757 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011758 ++NumCombined;
11759 return 0;
11760 }
11761
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011762 // If the pointer destination is a cast, see if we can fold the cast into the
11763 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011764 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011765 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11766 return Res;
11767 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011768 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011769 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11770 return Res;
11771
Chris Lattner408902b2005-09-12 23:23:25 +000011772
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011773 // If this store is the last instruction in the basic block (possibly
11774 // excepting debug info instructions and the pointer bitcasts that feed
11775 // into them), and if the block ends with an unconditional branch, try
11776 // to move it to the successor block.
11777 BBI = &SI;
11778 do {
11779 ++BBI;
11780 } while (isa<DbgInfoIntrinsic>(BBI) ||
11781 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011782 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011783 if (BI->isUnconditional())
11784 if (SimplifyStoreAtEndOfBlock(SI))
11785 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011786
Chris Lattner2f503e62005-01-31 05:36:43 +000011787 return 0;
11788}
11789
Chris Lattner3284d1f2007-04-15 00:07:55 +000011790/// SimplifyStoreAtEndOfBlock - Turn things like:
11791/// if () { *P = v1; } else { *P = v2 }
11792/// into a phi node with a store in the successor.
11793///
Chris Lattner31755a02007-04-15 01:02:18 +000011794/// Simplify things like:
11795/// *P = v1; if () { *P = v2; }
11796/// into a phi node with a store in the successor.
11797///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011798bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11799 BasicBlock *StoreBB = SI.getParent();
11800
11801 // Check to see if the successor block has exactly two incoming edges. If
11802 // so, see if the other predecessor contains a store to the same location.
11803 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011804 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011805
11806 // Determine whether Dest has exactly two predecessors and, if so, compute
11807 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011808 pred_iterator PI = pred_begin(DestBB);
11809 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011810 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011811 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011812 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011813 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011814 return false;
11815
11816 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011817 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011818 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011819 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011820 }
Chris Lattner31755a02007-04-15 01:02:18 +000011821 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011822 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011823
11824 // Bail out if all the relevant blocks aren't distinct (this can happen,
11825 // for example, if SI is in an infinite loop)
11826 if (StoreBB == DestBB || OtherBB == DestBB)
11827 return false;
11828
Chris Lattner31755a02007-04-15 01:02:18 +000011829 // Verify that the other block ends in a branch and is not otherwise empty.
11830 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011831 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011832 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011833 return false;
11834
Chris Lattner31755a02007-04-15 01:02:18 +000011835 // If the other block ends in an unconditional branch, check for the 'if then
11836 // else' case. there is an instruction before the branch.
11837 StoreInst *OtherStore = 0;
11838 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011839 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011840 // Skip over debugging info.
11841 while (isa<DbgInfoIntrinsic>(BBI) ||
11842 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11843 if (BBI==OtherBB->begin())
11844 return false;
11845 --BBI;
11846 }
11847 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011848 OtherStore = dyn_cast<StoreInst>(BBI);
11849 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11850 return false;
11851 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011852 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011853 // destinations is StoreBB, then we have the if/then case.
11854 if (OtherBr->getSuccessor(0) != StoreBB &&
11855 OtherBr->getSuccessor(1) != StoreBB)
11856 return false;
11857
11858 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011859 // if/then triangle. See if there is a store to the same ptr as SI that
11860 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011861 for (;; --BBI) {
11862 // Check to see if we find the matching store.
11863 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11864 if (OtherStore->getOperand(1) != SI.getOperand(1))
11865 return false;
11866 break;
11867 }
Eli Friedman6903a242008-06-13 22:02:12 +000011868 // If we find something that may be using or overwriting the stored
11869 // value, or if we run out of instructions, we can't do the xform.
11870 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011871 BBI == OtherBB->begin())
11872 return false;
11873 }
11874
11875 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011876 // make sure nothing reads or overwrites the stored value in
11877 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011878 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11879 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011880 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011881 return false;
11882 }
11883 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011884
Chris Lattner31755a02007-04-15 01:02:18 +000011885 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011886 Value *MergedVal = OtherStore->getOperand(0);
11887 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011888 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011889 PN->reserveOperandSpace(2);
11890 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011891 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11892 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011893 }
11894
11895 // Advance to a place where it is safe to insert the new store and
11896 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011897 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011898 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11899 OtherStore->isVolatile()), *BBI);
11900
11901 // Nuke the old stores.
11902 EraseInstFromFunction(SI);
11903 EraseInstFromFunction(*OtherStore);
11904 ++NumCombined;
11905 return true;
11906}
11907
Chris Lattner2f503e62005-01-31 05:36:43 +000011908
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011909Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11910 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011911 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011912 BasicBlock *TrueDest;
11913 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011914 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011915 !isa<Constant>(X)) {
11916 // Swap Destinations and condition...
11917 BI.setCondition(X);
11918 BI.setSuccessor(0, FalseDest);
11919 BI.setSuccessor(1, TrueDest);
11920 return &BI;
11921 }
11922
Reid Spencere4d87aa2006-12-23 06:05:41 +000011923 // Cannonicalize fcmp_one -> fcmp_oeq
11924 FCmpInst::Predicate FPred; Value *Y;
11925 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011926 TrueDest, FalseDest)) &&
11927 BI.getCondition()->hasOneUse())
11928 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11929 FPred == FCmpInst::FCMP_OGE) {
11930 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11931 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11932
11933 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011934 BI.setSuccessor(0, FalseDest);
11935 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011936 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011937 return &BI;
11938 }
11939
11940 // Cannonicalize icmp_ne -> icmp_eq
11941 ICmpInst::Predicate IPred;
11942 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011943 TrueDest, FalseDest)) &&
11944 BI.getCondition()->hasOneUse())
11945 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11946 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11947 IPred == ICmpInst::ICMP_SGE) {
11948 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11949 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11950 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011951 BI.setSuccessor(0, FalseDest);
11952 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011953 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011954 return &BI;
11955 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011956
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011957 return 0;
11958}
Chris Lattner0864acf2002-11-04 16:18:53 +000011959
Chris Lattner46238a62004-07-03 00:26:11 +000011960Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11961 Value *Cond = SI.getCondition();
11962 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11963 if (I->getOpcode() == Instruction::Add)
11964 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11965 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11966 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011967 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011968 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011969 AddRHS));
11970 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011971 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011972 return &SI;
11973 }
11974 }
11975 return 0;
11976}
11977
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011978Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011979 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011980
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011981 if (!EV.hasIndices())
11982 return ReplaceInstUsesWith(EV, Agg);
11983
11984 if (Constant *C = dyn_cast<Constant>(Agg)) {
11985 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011986 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011987
11988 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011989 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011990
11991 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11992 // Extract the element indexed by the first index out of the constant
11993 Value *V = C->getOperand(*EV.idx_begin());
11994 if (EV.getNumIndices() > 1)
11995 // Extract the remaining indices out of the constant indexed by the
11996 // first index
11997 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11998 else
11999 return ReplaceInstUsesWith(EV, V);
12000 }
12001 return 0; // Can't handle other constants
12002 }
12003 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12004 // We're extracting from an insertvalue instruction, compare the indices
12005 const unsigned *exti, *exte, *insi, *inse;
12006 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12007 exte = EV.idx_end(), inse = IV->idx_end();
12008 exti != exte && insi != inse;
12009 ++exti, ++insi) {
12010 if (*insi != *exti)
12011 // The insert and extract both reference distinctly different elements.
12012 // This means the extract is not influenced by the insert, and we can
12013 // replace the aggregate operand of the extract with the aggregate
12014 // operand of the insert. i.e., replace
12015 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12016 // %E = extractvalue { i32, { i32 } } %I, 0
12017 // with
12018 // %E = extractvalue { i32, { i32 } } %A, 0
12019 return ExtractValueInst::Create(IV->getAggregateOperand(),
12020 EV.idx_begin(), EV.idx_end());
12021 }
12022 if (exti == exte && insi == inse)
12023 // Both iterators are at the end: Index lists are identical. Replace
12024 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12025 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12026 // with "i32 42"
12027 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12028 if (exti == exte) {
12029 // The extract list is a prefix of the insert list. i.e. replace
12030 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12031 // %E = extractvalue { i32, { i32 } } %I, 1
12032 // with
12033 // %X = extractvalue { i32, { i32 } } %A, 1
12034 // %E = insertvalue { i32 } %X, i32 42, 0
12035 // by switching the order of the insert and extract (though the
12036 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012037 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12038 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012039 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12040 insi, inse);
12041 }
12042 if (insi == inse)
12043 // The insert list is a prefix of the extract list
12044 // We can simply remove the common indices from the extract and make it
12045 // operate on the inserted value instead of the insertvalue result.
12046 // i.e., replace
12047 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12048 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12049 // with
12050 // %E extractvalue { i32 } { i32 42 }, 0
12051 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12052 exti, exte);
12053 }
12054 // Can't simplify extracts from other values. Note that nested extracts are
12055 // already simplified implicitely by the above (extract ( extract (insert) )
12056 // will be translated into extract ( insert ( extract ) ) first and then just
12057 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012058 return 0;
12059}
12060
Chris Lattner220b0cf2006-03-05 00:22:33 +000012061/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12062/// is to leave as a vector operation.
12063static bool CheapToScalarize(Value *V, bool isConstant) {
12064 if (isa<ConstantAggregateZero>(V))
12065 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012066 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012067 if (isConstant) return true;
12068 // If all elts are the same, we can extract.
12069 Constant *Op0 = C->getOperand(0);
12070 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12071 if (C->getOperand(i) != Op0)
12072 return false;
12073 return true;
12074 }
12075 Instruction *I = dyn_cast<Instruction>(V);
12076 if (!I) return false;
12077
12078 // Insert element gets simplified to the inserted element or is deleted if
12079 // this is constant idx extract element and its a constant idx insertelt.
12080 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12081 isa<ConstantInt>(I->getOperand(2)))
12082 return true;
12083 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12084 return true;
12085 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12086 if (BO->hasOneUse() &&
12087 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12088 CheapToScalarize(BO->getOperand(1), isConstant)))
12089 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012090 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12091 if (CI->hasOneUse() &&
12092 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12093 CheapToScalarize(CI->getOperand(1), isConstant)))
12094 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012095
12096 return false;
12097}
12098
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012099/// Read and decode a shufflevector mask.
12100///
12101/// It turns undef elements into values that are larger than the number of
12102/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012103static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12104 unsigned NElts = SVI->getType()->getNumElements();
12105 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12106 return std::vector<unsigned>(NElts, 0);
12107 if (isa<UndefValue>(SVI->getOperand(2)))
12108 return std::vector<unsigned>(NElts, 2*NElts);
12109
12110 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012111 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012112 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12113 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012114 Result.push_back(NElts*2); // undef -> 8
12115 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012116 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012117 return Result;
12118}
12119
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012120/// FindScalarElement - Given a vector and an element number, see if the scalar
12121/// value is already around as a register, for example if it were inserted then
12122/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012123static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012124 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012125 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12126 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012127 unsigned Width = PTy->getNumElements();
12128 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012129 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012130
12131 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012132 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012133 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012134 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012135 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012136 return CP->getOperand(EltNo);
12137 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12138 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012139 if (!isa<ConstantInt>(III->getOperand(2)))
12140 return 0;
12141 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012142
12143 // If this is an insert to the element we are looking for, return the
12144 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012145 if (EltNo == IIElt)
12146 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012147
12148 // Otherwise, the insertelement doesn't modify the value, recurse on its
12149 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012150 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012151 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012152 unsigned LHSWidth =
12153 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012154 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012155 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012156 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012157 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012158 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012159 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012160 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012161 }
12162
12163 // Otherwise, we don't know.
12164 return 0;
12165}
12166
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012167Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012168 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012169 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012170 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012171
Dan Gohman07a96762007-07-16 14:29:03 +000012172 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012173 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012174 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012175
Reid Spencer9d6565a2007-02-15 02:26:10 +000012176 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012177 // If vector val is constant with all elements the same, replace EI with
12178 // that element. When the elements are not identical, we cannot replace yet
12179 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012180 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012181 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012182 if (C->getOperand(i) != op0) {
12183 op0 = 0;
12184 break;
12185 }
12186 if (op0)
12187 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012188 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012189
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012190 // If extracting a specified index from the vector, see if we can recursively
12191 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012192 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012193 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012194 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012195
12196 // If this is extracting an invalid index, turn this into undef, to avoid
12197 // crashing the code below.
12198 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012199 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012200
Chris Lattner867b99f2006-10-05 06:55:50 +000012201 // This instruction only demands the single element from the input vector.
12202 // If the input vector has a single use, simplify it based on this use
12203 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012204 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012205 APInt UndefElts(VectorWidth, 0);
12206 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012207 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012208 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012209 EI.setOperand(0, V);
12210 return &EI;
12211 }
12212 }
12213
Owen Andersond672ecb2009-07-03 00:17:18 +000012214 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012215 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012216
12217 // If the this extractelement is directly using a bitcast from a vector of
12218 // the same number of elements, see if we can find the source element from
12219 // it. In this case, we will end up needing to bitcast the scalars.
12220 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12221 if (const VectorType *VT =
12222 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12223 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012224 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12225 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012226 return new BitCastInst(Elt, EI.getType());
12227 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012228 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012229
Chris Lattner73fa49d2006-05-25 22:53:38 +000012230 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012231 // Push extractelement into predecessor operation if legal and
12232 // profitable to do so
12233 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12234 if (I->hasOneUse() &&
12235 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12236 Value *newEI0 =
12237 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12238 EI.getName()+".lhs");
12239 Value *newEI1 =
12240 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12241 EI.getName()+".rhs");
12242 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012243 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012244 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012245 // Extracting the inserted element?
12246 if (IE->getOperand(2) == EI.getOperand(1))
12247 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12248 // If the inserted and extracted elements are constants, they must not
12249 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012250 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012251 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012252 EI.setOperand(0, IE->getOperand(0));
12253 return &EI;
12254 }
12255 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12256 // If this is extracting an element from a shufflevector, figure out where
12257 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012258 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12259 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012260 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012261 unsigned LHSWidth =
12262 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12263
12264 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012265 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012266 else if (SrcIdx < LHSWidth*2) {
12267 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012268 Src = SVI->getOperand(1);
12269 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012270 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012271 }
Eric Christophera3500da2009-07-25 02:28:41 +000012272 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012273 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12274 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012275 }
12276 }
Eli Friedman2451a642009-07-18 23:06:53 +000012277 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012278 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012279 return 0;
12280}
12281
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012282/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12283/// elements from either LHS or RHS, return the shuffle mask and true.
12284/// Otherwise, return false.
12285static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012286 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012287 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012288 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12289 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012290 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012291
12292 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012293 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012294 return true;
12295 } else if (V == LHS) {
12296 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012297 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012298 return true;
12299 } else if (V == RHS) {
12300 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012301 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012302 return true;
12303 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12304 // If this is an insert of an extract from some other vector, include it.
12305 Value *VecOp = IEI->getOperand(0);
12306 Value *ScalarOp = IEI->getOperand(1);
12307 Value *IdxOp = IEI->getOperand(2);
12308
Chris Lattnerd929f062006-04-27 21:14:21 +000012309 if (!isa<ConstantInt>(IdxOp))
12310 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012311 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012312
12313 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12314 // Okay, we can handle this if the vector we are insertinting into is
12315 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012316 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012317 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012318 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012319 return true;
12320 }
12321 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12322 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012323 EI->getOperand(0)->getType() == V->getType()) {
12324 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012325 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012326
12327 // This must be extracting from either LHS or RHS.
12328 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12329 // Okay, we can handle this if the vector we are insertinting into is
12330 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012331 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012332 // If so, update the mask to reflect the inserted value.
12333 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012334 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012335 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012336 } else {
12337 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012338 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012339 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012340
12341 }
12342 return true;
12343 }
12344 }
12345 }
12346 }
12347 }
12348 // TODO: Handle shufflevector here!
12349
12350 return false;
12351}
12352
12353/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12354/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12355/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012356static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012357 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012358 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012359 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012360 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012361 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012362
12363 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012364 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012365 return V;
12366 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012367 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012368 return V;
12369 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12370 // If this is an insert of an extract from some other vector, include it.
12371 Value *VecOp = IEI->getOperand(0);
12372 Value *ScalarOp = IEI->getOperand(1);
12373 Value *IdxOp = IEI->getOperand(2);
12374
12375 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12376 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12377 EI->getOperand(0)->getType() == V->getType()) {
12378 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012379 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12380 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012381
12382 // Either the extracted from or inserted into vector must be RHSVec,
12383 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012384 if (EI->getOperand(0) == RHS || RHS == 0) {
12385 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012386 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012387 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012388 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012389 return V;
12390 }
12391
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012392 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012393 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12394 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012395 // Everything but the extracted element is replaced with the RHS.
12396 for (unsigned i = 0; i != NumElts; ++i) {
12397 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012398 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012399 }
12400 return V;
12401 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012402
12403 // If this insertelement is a chain that comes from exactly these two
12404 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012405 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12406 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012407 return EI->getOperand(0);
12408
Chris Lattnerefb47352006-04-15 01:39:45 +000012409 }
12410 }
12411 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012412 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012413
12414 // Otherwise, can't do anything fancy. Return an identity vector.
12415 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012416 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012417 return V;
12418}
12419
12420Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12421 Value *VecOp = IE.getOperand(0);
12422 Value *ScalarOp = IE.getOperand(1);
12423 Value *IdxOp = IE.getOperand(2);
12424
Chris Lattner599ded12007-04-09 01:11:16 +000012425 // Inserting an undef or into an undefined place, remove this.
12426 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12427 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012428
Chris Lattnerefb47352006-04-15 01:39:45 +000012429 // If the inserted element was extracted from some other vector, and if the
12430 // indexes are constant, try to turn this into a shufflevector operation.
12431 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12432 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12433 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012434 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012435 unsigned ExtractedIdx =
12436 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012437 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012438
12439 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12440 return ReplaceInstUsesWith(IE, VecOp);
12441
12442 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012443 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012444
12445 // If we are extracting a value from a vector, then inserting it right
12446 // back into the same place, just use the input vector.
12447 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12448 return ReplaceInstUsesWith(IE, VecOp);
12449
12450 // We could theoretically do this for ANY input. However, doing so could
12451 // turn chains of insertelement instructions into a chain of shufflevector
12452 // instructions, and right now we do not merge shufflevectors. As such,
12453 // only do this in a situation where it is clear that there is benefit.
12454 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12455 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12456 // the values of VecOp, except then one read from EIOp0.
12457 // Build a new shuffle mask.
12458 std::vector<Constant*> Mask;
12459 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012460 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012461 else {
12462 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012463 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012464 NumVectorElts));
12465 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012466 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012467 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012468 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012469 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012470 }
12471
12472 // If this insertelement isn't used by some other insertelement, turn it
12473 // (and any insertelements it points to), into one big shuffle.
12474 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12475 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012476 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012477 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012478 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012479 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012480 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012481 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012482 }
12483 }
12484 }
12485
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012486 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12487 APInt UndefElts(VWidth, 0);
12488 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12489 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12490 return &IE;
12491
Chris Lattnerefb47352006-04-15 01:39:45 +000012492 return 0;
12493}
12494
12495
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012496Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12497 Value *LHS = SVI.getOperand(0);
12498 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012499 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012500
12501 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012502
Chris Lattner867b99f2006-10-05 06:55:50 +000012503 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012504 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012505 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012506
Dan Gohman488fbfc2008-09-09 18:11:14 +000012507 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012508
12509 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12510 return 0;
12511
Evan Cheng388df622009-02-03 10:05:09 +000012512 APInt UndefElts(VWidth, 0);
12513 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12514 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012515 LHS = SVI.getOperand(0);
12516 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012517 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012518 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012519
Chris Lattner863bcff2006-05-25 23:48:38 +000012520 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12521 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12522 if (LHS == RHS || isa<UndefValue>(LHS)) {
12523 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012524 // shuffle(undef,undef,mask) -> undef.
12525 return ReplaceInstUsesWith(SVI, LHS);
12526 }
12527
Chris Lattner863bcff2006-05-25 23:48:38 +000012528 // Remap any references to RHS to use LHS.
12529 std::vector<Constant*> Elts;
12530 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012531 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012532 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012533 else {
12534 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012535 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012536 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012537 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012538 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012539 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012540 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012541 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012542 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012543 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012544 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012545 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012546 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012547 LHS = SVI.getOperand(0);
12548 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012549 MadeChange = true;
12550 }
12551
Chris Lattner7b2e27922006-05-26 00:29:06 +000012552 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012553 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012554
Chris Lattner863bcff2006-05-25 23:48:38 +000012555 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12556 if (Mask[i] >= e*2) continue; // Ignore undef values.
12557 // Is this an identity shuffle of the LHS value?
12558 isLHSID &= (Mask[i] == i);
12559
12560 // Is this an identity shuffle of the RHS value?
12561 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012562 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012563
Chris Lattner863bcff2006-05-25 23:48:38 +000012564 // Eliminate identity shuffles.
12565 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12566 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012567
Chris Lattner7b2e27922006-05-26 00:29:06 +000012568 // If the LHS is a shufflevector itself, see if we can combine it with this
12569 // one without producing an unusual shuffle. Here we are really conservative:
12570 // we are absolutely afraid of producing a shuffle mask not in the input
12571 // program, because the code gen may not be smart enough to turn a merged
12572 // shuffle into two specific shuffles: it may produce worse code. As such,
12573 // we only merge two shuffles if the result is one of the two input shuffle
12574 // masks. In this case, merging the shuffles just removes one instruction,
12575 // which we know is safe. This is good for things like turning:
12576 // (splat(splat)) -> splat.
12577 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12578 if (isa<UndefValue>(RHS)) {
12579 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12580
12581 std::vector<unsigned> NewMask;
12582 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12583 if (Mask[i] >= 2*e)
12584 NewMask.push_back(2*e);
12585 else
12586 NewMask.push_back(LHSMask[Mask[i]]);
12587
12588 // If the result mask is equal to the src shuffle or this shuffle mask, do
12589 // the replacement.
12590 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012591 unsigned LHSInNElts =
12592 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012593 std::vector<Constant*> Elts;
12594 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012595 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012596 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012597 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012598 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012599 }
12600 }
12601 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12602 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012603 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012604 }
12605 }
12606 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012607
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012608 return MadeChange ? &SVI : 0;
12609}
12610
12611
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012612
Chris Lattnerea1c4542004-12-08 23:43:58 +000012613
12614/// TryToSinkInstruction - Try to move the specified instruction from its
12615/// current block into the beginning of DestBlock, which can only happen if it's
12616/// safe to move the instruction past all of the instructions between it and the
12617/// end of its block.
12618static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12619 assert(I->hasOneUse() && "Invariants didn't hold!");
12620
Chris Lattner108e9022005-10-27 17:13:11 +000012621 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012622 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012623 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012624
Chris Lattnerea1c4542004-12-08 23:43:58 +000012625 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012626 if (isa<AllocaInst>(I) && I->getParent() ==
12627 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012628 return false;
12629
Chris Lattner96a52a62004-12-09 07:14:34 +000012630 // We can only sink load instructions if there is nothing between the load and
12631 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012632 if (I->mayReadFromMemory()) {
12633 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012634 Scan != E; ++Scan)
12635 if (Scan->mayWriteToMemory())
12636 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012637 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012638
Dan Gohman02dea8b2008-05-23 21:05:58 +000012639 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012640
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012641 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012642 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012643 ++NumSunkInst;
12644 return true;
12645}
12646
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012647
12648/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12649/// all reachable code to the worklist.
12650///
12651/// This has a couple of tricks to make the code faster and more powerful. In
12652/// particular, we constant fold and DCE instructions as we go, to avoid adding
12653/// them to the worklist (this significantly speeds up instcombine on code where
12654/// many instructions are dead or constant). Additionally, if we find a branch
12655/// whose condition is a known constant, we only visit the reachable successors.
12656///
12657static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012658 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012659 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012660 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012661 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012662 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012663
Chris Lattner2c7718a2007-03-23 19:17:18 +000012664 while (!Worklist.empty()) {
12665 BB = Worklist.back();
12666 Worklist.pop_back();
12667
12668 // We have now visited this block! If we've already been here, ignore it.
12669 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012670
12671 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012672 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12673 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012674
Chris Lattner2c7718a2007-03-23 19:17:18 +000012675 // DCE instruction if trivially dead.
12676 if (isInstructionTriviallyDead(Inst)) {
12677 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012678 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012679 Inst->eraseFromParent();
12680 continue;
12681 }
12682
12683 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012684 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012685 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12686 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012687 Inst->replaceAllUsesWith(C);
12688 ++NumConstProp;
12689 Inst->eraseFromParent();
12690 continue;
12691 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012692
Devang Patel7fe1dec2008-11-19 18:56:50 +000012693 // If there are two consecutive llvm.dbg.stoppoint calls then
12694 // it is likely that the optimizer deleted code in between these
12695 // two intrinsics.
12696 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12697 if (DBI_Next) {
12698 if (DBI_Prev
12699 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12700 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012701 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012702 DBI_Prev->eraseFromParent();
12703 }
12704 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012705 } else {
12706 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012707 }
12708
Chris Lattner61488a32009-10-11 21:05:34 +000012709 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012710 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012711
12712 // Recursively visit successors. If this is a branch or switch on a
12713 // constant, only visit the reachable successor.
12714 TerminatorInst *TI = BB->getTerminator();
12715 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12716 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12717 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012718 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012719 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012720 continue;
12721 }
12722 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12723 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12724 // See if this is an explicit destination.
12725 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12726 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012727 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012728 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012729 continue;
12730 }
12731
12732 // Otherwise it is the default destination.
12733 Worklist.push_back(SI->getSuccessor(0));
12734 continue;
12735 }
12736 }
12737
12738 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12739 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012740 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012741}
12742
Chris Lattnerec9c3582007-03-03 02:04:50 +000012743bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012744 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012745 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012746
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012747 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12748 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012749
Chris Lattnerb3d59702005-07-07 20:40:38 +000012750 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012751 // Do a depth-first traversal of the function, populate the worklist with
12752 // the reachable instructions. Ignore blocks that are not reachable. Keep
12753 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012754 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012755 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012756
Chris Lattnerb3d59702005-07-07 20:40:38 +000012757 // Do a quick scan over the function. If we find any blocks that are
12758 // unreachable, remove any instructions inside of them. This prevents
12759 // the instcombine code from having to deal with some bad special cases.
12760 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12761 if (!Visited.count(BB)) {
12762 Instruction *Term = BB->getTerminator();
12763 while (Term != BB->begin()) { // Remove instrs bottom-up
12764 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012765
Chris Lattnerbdff5482009-08-23 04:37:46 +000012766 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012767 // A debug intrinsic shouldn't force another iteration if we weren't
12768 // going to do one without it.
12769 if (!isa<DbgInfoIntrinsic>(I)) {
12770 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012771 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012772 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012773 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012774 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012775 I->eraseFromParent();
12776 }
12777 }
12778 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012779
Chris Lattner873ff012009-08-30 05:55:36 +000012780 while (!Worklist.isEmpty()) {
12781 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012782 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012783
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012784 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012785 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012786 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012787 EraseInstFromFunction(*I);
12788 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012789 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012790 continue;
12791 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012792
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012793 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012794 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012795 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012796
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012797 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012798 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012799 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012800 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012801 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012802 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012803 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012804
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012805 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012806 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012807 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12808 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012809 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12810 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012811 if (NewC != CE) {
Dan Gohmane41a1152009-10-05 16:31:55 +000012812 *i = NewC;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012813 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012814 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012815 }
12816
Chris Lattnerea1c4542004-12-08 23:43:58 +000012817 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012818 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012819 BasicBlock *BB = I->getParent();
12820 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12821 if (UserParent != BB) {
12822 bool UserIsSuccessor = false;
12823 // See if the user is one of our successors.
12824 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12825 if (*SI == UserParent) {
12826 UserIsSuccessor = true;
12827 break;
12828 }
12829
12830 // If the user is one of our immediate successors, and if that successor
12831 // only has us as a predecessors (we'd have to split the critical edge
12832 // otherwise), we can keep going.
12833 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12834 next(pred_begin(UserParent)) == pred_end(UserParent))
12835 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012836 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012837 }
12838 }
12839
Chris Lattner74381062009-08-30 07:44:24 +000012840 // Now that we have an instruction, try combining it to simplify it.
12841 Builder->SetInsertPoint(I->getParent(), I);
12842
Reid Spencera9b81012007-03-26 17:44:01 +000012843#ifndef NDEBUG
12844 std::string OrigI;
12845#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012846 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000012847 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12848
Chris Lattner90ac28c2002-08-02 19:29:35 +000012849 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012850 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012851 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012852 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012853 DEBUG(errs() << "IC: Old = " << *I << '\n'
12854 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012855
Chris Lattnerf523d062004-06-09 05:08:07 +000012856 // Everything uses the new instruction now.
12857 I->replaceAllUsesWith(Result);
12858
12859 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012860 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012861 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012862
Chris Lattner6934a042007-02-11 01:23:03 +000012863 // Move the name to the new instruction first.
12864 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012865
12866 // Insert the new instruction into the basic block...
12867 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012868 BasicBlock::iterator InsertPos = I;
12869
12870 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12871 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12872 ++InsertPos;
12873
12874 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012875
Chris Lattner7a1e9242009-08-30 06:13:40 +000012876 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012877 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012878#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012879 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12880 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012881#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012882
Chris Lattner90ac28c2002-08-02 19:29:35 +000012883 // If the instruction was modified, it's possible that it is now dead.
12884 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012885 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012886 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012887 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012888 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012889 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012890 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012891 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012892 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012893 }
12894 }
12895
Chris Lattner873ff012009-08-30 05:55:36 +000012896 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012897 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012898}
12899
Chris Lattnerec9c3582007-03-03 02:04:50 +000012900
12901bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012902 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012903 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012904
Chris Lattner74381062009-08-30 07:44:24 +000012905
12906 /// Builder - This is an IRBuilder that automatically inserts new
12907 /// instructions into the worklist when they are created.
12908 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12909 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12910 InstCombineIRInserter(Worklist));
12911 Builder = &TheBuilder;
12912
Chris Lattnerec9c3582007-03-03 02:04:50 +000012913 bool EverMadeChange = false;
12914
12915 // Iterate while there is work to do.
12916 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012917 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012918 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012919
12920 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012921 return EverMadeChange;
12922}
12923
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012924FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012925 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012926}