Use the new script to sort the includes of every file under lib.
[oota-llvm.git] / lib / Analysis / InlineCost.cpp
1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements inline cost analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "inline-cost"
15 #include "llvm/Analysis/InlineCost.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DataLayout.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/InstVisitor.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Operator.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/raw_ostream.h"
33
34 using namespace llvm;
35
36 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
37
38 namespace {
39
40 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
41   typedef InstVisitor<CallAnalyzer, bool> Base;
42   friend class InstVisitor<CallAnalyzer, bool>;
43
44   // DataLayout if available, or null.
45   const DataLayout *const TD;
46
47   // The called function.
48   Function &F;
49
50   int Threshold;
51   int Cost;
52
53   bool IsCallerRecursive;
54   bool IsRecursiveCall;
55   bool ExposesReturnsTwice;
56   bool HasDynamicAlloca;
57   /// Number of bytes allocated statically by the callee.
58   uint64_t AllocatedSize;
59   unsigned NumInstructions, NumVectorInstructions;
60   int FiftyPercentVectorBonus, TenPercentVectorBonus;
61   int VectorBonus;
62
63   // While we walk the potentially-inlined instructions, we build up and
64   // maintain a mapping of simplified values specific to this callsite. The
65   // idea is to propagate any special information we have about arguments to
66   // this call through the inlinable section of the function, and account for
67   // likely simplifications post-inlining. The most important aspect we track
68   // is CFG altering simplifications -- when we prove a basic block dead, that
69   // can cause dramatic shifts in the cost of inlining a function.
70   DenseMap<Value *, Constant *> SimplifiedValues;
71
72   // Keep track of the values which map back (through function arguments) to
73   // allocas on the caller stack which could be simplified through SROA.
74   DenseMap<Value *, Value *> SROAArgValues;
75
76   // The mapping of caller Alloca values to their accumulated cost savings. If
77   // we have to disable SROA for one of the allocas, this tells us how much
78   // cost must be added.
79   DenseMap<Value *, int> SROAArgCosts;
80
81   // Keep track of values which map to a pointer base and constant offset.
82   DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
83
84   // Custom simplification helper routines.
85   bool isAllocaDerivedArg(Value *V);
86   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
87                             DenseMap<Value *, int>::iterator &CostIt);
88   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
89   void disableSROA(Value *V);
90   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
91                           int InstructionCost);
92   bool handleSROACandidate(bool IsSROAValid,
93                            DenseMap<Value *, int>::iterator CostIt,
94                            int InstructionCost);
95   bool isGEPOffsetConstant(GetElementPtrInst &GEP);
96   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
97   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
98
99   // Custom analysis routines.
100   bool analyzeBlock(BasicBlock *BB);
101
102   // Disable several entry points to the visitor so we don't accidentally use
103   // them by declaring but not defining them here.
104   void visit(Module *);     void visit(Module &);
105   void visit(Function *);   void visit(Function &);
106   void visit(BasicBlock *); void visit(BasicBlock &);
107
108   // Provide base case for our instruction visit.
109   bool visitInstruction(Instruction &I);
110
111   // Our visit overrides.
112   bool visitAlloca(AllocaInst &I);
113   bool visitPHI(PHINode &I);
114   bool visitGetElementPtr(GetElementPtrInst &I);
115   bool visitBitCast(BitCastInst &I);
116   bool visitPtrToInt(PtrToIntInst &I);
117   bool visitIntToPtr(IntToPtrInst &I);
118   bool visitCastInst(CastInst &I);
119   bool visitUnaryInstruction(UnaryInstruction &I);
120   bool visitICmp(ICmpInst &I);
121   bool visitSub(BinaryOperator &I);
122   bool visitBinaryOperator(BinaryOperator &I);
123   bool visitLoad(LoadInst &I);
124   bool visitStore(StoreInst &I);
125   bool visitCallSite(CallSite CS);
126
127 public:
128   CallAnalyzer(const DataLayout *TD, Function &Callee, int Threshold)
129     : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
130       IsCallerRecursive(false), IsRecursiveCall(false),
131       ExposesReturnsTwice(false), HasDynamicAlloca(false), AllocatedSize(0),
132       NumInstructions(0), NumVectorInstructions(0),
133       FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
134       NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
135       NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
136       NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLost(0) {
137   }
138
139   bool analyzeCall(CallSite CS);
140
141   int getThreshold() { return Threshold; }
142   int getCost() { return Cost; }
143
144   // Keep a bunch of stats about the cost savings found so we can print them
145   // out when debugging.
146   unsigned NumConstantArgs;
147   unsigned NumConstantOffsetPtrArgs;
148   unsigned NumAllocaArgs;
149   unsigned NumConstantPtrCmps;
150   unsigned NumConstantPtrDiffs;
151   unsigned NumInstructionsSimplified;
152   unsigned SROACostSavings;
153   unsigned SROACostSavingsLost;
154
155   void dump();
156 };
157
158 } // namespace
159
160 /// \brief Test whether the given value is an Alloca-derived function argument.
161 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
162   return SROAArgValues.count(V);
163 }
164
165 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
166 /// Returns false if V does not map to a SROA-candidate.
167 bool CallAnalyzer::lookupSROAArgAndCost(
168     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
169   if (SROAArgValues.empty() || SROAArgCosts.empty())
170     return false;
171
172   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
173   if (ArgIt == SROAArgValues.end())
174     return false;
175
176   Arg = ArgIt->second;
177   CostIt = SROAArgCosts.find(Arg);
178   return CostIt != SROAArgCosts.end();
179 }
180
181 /// \brief Disable SROA for the candidate marked by this cost iterator.
182 ///
183 /// This marks the candidate as no longer viable for SROA, and adds the cost
184 /// savings associated with it back into the inline cost measurement.
185 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
186   // If we're no longer able to perform SROA we need to undo its cost savings
187   // and prevent subsequent analysis.
188   Cost += CostIt->second;
189   SROACostSavings -= CostIt->second;
190   SROACostSavingsLost += CostIt->second;
191   SROAArgCosts.erase(CostIt);
192 }
193
194 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
195 void CallAnalyzer::disableSROA(Value *V) {
196   Value *SROAArg;
197   DenseMap<Value *, int>::iterator CostIt;
198   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
199     disableSROA(CostIt);
200 }
201
202 /// \brief Accumulate the given cost for a particular SROA candidate.
203 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
204                                       int InstructionCost) {
205   CostIt->second += InstructionCost;
206   SROACostSavings += InstructionCost;
207 }
208
209 /// \brief Helper for the common pattern of handling a SROA candidate.
210 /// Either accumulates the cost savings if the SROA remains valid, or disables
211 /// SROA for the candidate.
212 bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
213                                        DenseMap<Value *, int>::iterator CostIt,
214                                        int InstructionCost) {
215   if (IsSROAValid) {
216     accumulateSROACost(CostIt, InstructionCost);
217     return true;
218   }
219
220   disableSROA(CostIt);
221   return false;
222 }
223
224 /// \brief Check whether a GEP's indices are all constant.
225 ///
226 /// Respects any simplified values known during the analysis of this callsite.
227 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
228   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
229     if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
230       return false;
231
232   return true;
233 }
234
235 /// \brief Accumulate a constant GEP offset into an APInt if possible.
236 ///
237 /// Returns false if unable to compute the offset for any reason. Respects any
238 /// simplified values known during the analysis of this callsite.
239 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
240   if (!TD)
241     return false;
242
243   unsigned IntPtrWidth = TD->getPointerSizeInBits();
244   assert(IntPtrWidth == Offset.getBitWidth());
245
246   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
247        GTI != GTE; ++GTI) {
248     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
249     if (!OpC)
250       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
251         OpC = dyn_cast<ConstantInt>(SimpleOp);
252     if (!OpC)
253       return false;
254     if (OpC->isZero()) continue;
255
256     // Handle a struct index, which adds its field offset to the pointer.
257     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
258       unsigned ElementIdx = OpC->getZExtValue();
259       const StructLayout *SL = TD->getStructLayout(STy);
260       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
261       continue;
262     }
263
264     APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
265     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
266   }
267   return true;
268 }
269
270 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
271   // FIXME: Check whether inlining will turn a dynamic alloca into a static
272   // alloca, and handle that case.
273
274   // Accumulate the allocated size.
275   if (I.isStaticAlloca()) {
276     Type *Ty = I.getAllocatedType();
277     AllocatedSize += (TD ? TD->getTypeAllocSize(Ty) :
278                       Ty->getPrimitiveSizeInBits());
279   }
280
281   // We will happily inline static alloca instructions.
282   if (I.isStaticAlloca())
283     return Base::visitAlloca(I);
284
285   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
286   // a variety of reasons, and so we would like to not inline them into
287   // functions which don't currently have a dynamic alloca. This simply
288   // disables inlining altogether in the presence of a dynamic alloca.
289   HasDynamicAlloca = true;
290   return false;
291 }
292
293 bool CallAnalyzer::visitPHI(PHINode &I) {
294   // FIXME: We should potentially be tracking values through phi nodes,
295   // especially when they collapse to a single value due to deleted CFG edges
296   // during inlining.
297
298   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
299   // though we don't want to propagate it's bonuses. The idea is to disable
300   // SROA if it *might* be used in an inappropriate manner.
301
302   // Phi nodes are always zero-cost.
303   return true;
304 }
305
306 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
307   Value *SROAArg;
308   DenseMap<Value *, int>::iterator CostIt;
309   bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
310                                             SROAArg, CostIt);
311
312   // Try to fold GEPs of constant-offset call site argument pointers. This
313   // requires target data and inbounds GEPs.
314   if (TD && I.isInBounds()) {
315     // Check if we have a base + offset for the pointer.
316     Value *Ptr = I.getPointerOperand();
317     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
318     if (BaseAndOffset.first) {
319       // Check if the offset of this GEP is constant, and if so accumulate it
320       // into Offset.
321       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
322         // Non-constant GEPs aren't folded, and disable SROA.
323         if (SROACandidate)
324           disableSROA(CostIt);
325         return false;
326       }
327
328       // Add the result as a new mapping to Base + Offset.
329       ConstantOffsetPtrs[&I] = BaseAndOffset;
330
331       // Also handle SROA candidates here, we already know that the GEP is
332       // all-constant indexed.
333       if (SROACandidate)
334         SROAArgValues[&I] = SROAArg;
335
336       return true;
337     }
338   }
339
340   if (isGEPOffsetConstant(I)) {
341     if (SROACandidate)
342       SROAArgValues[&I] = SROAArg;
343
344     // Constant GEPs are modeled as free.
345     return true;
346   }
347
348   // Variable GEPs will require math and will disable SROA.
349   if (SROACandidate)
350     disableSROA(CostIt);
351   return false;
352 }
353
354 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
355   // Propagate constants through bitcasts.
356   if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
357     if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
358       SimplifiedValues[&I] = C;
359       return true;
360     }
361
362   // Track base/offsets through casts
363   std::pair<Value *, APInt> BaseAndOffset
364     = ConstantOffsetPtrs.lookup(I.getOperand(0));
365   // Casts don't change the offset, just wrap it up.
366   if (BaseAndOffset.first)
367     ConstantOffsetPtrs[&I] = BaseAndOffset;
368
369   // Also look for SROA candidates here.
370   Value *SROAArg;
371   DenseMap<Value *, int>::iterator CostIt;
372   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
373     SROAArgValues[&I] = SROAArg;
374
375   // Bitcasts are always zero cost.
376   return true;
377 }
378
379 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
380   // Propagate constants through ptrtoint.
381   if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
382     if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
383       SimplifiedValues[&I] = C;
384       return true;
385     }
386
387   // Track base/offset pairs when converted to a plain integer provided the
388   // integer is large enough to represent the pointer.
389   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
390   if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
391     std::pair<Value *, APInt> BaseAndOffset
392       = ConstantOffsetPtrs.lookup(I.getOperand(0));
393     if (BaseAndOffset.first)
394       ConstantOffsetPtrs[&I] = BaseAndOffset;
395   }
396
397   // This is really weird. Technically, ptrtoint will disable SROA. However,
398   // unless that ptrtoint is *used* somewhere in the live basic blocks after
399   // inlining, it will be nuked, and SROA should proceed. All of the uses which
400   // would block SROA would also block SROA if applied directly to a pointer,
401   // and so we can just add the integer in here. The only places where SROA is
402   // preserved either cannot fire on an integer, or won't in-and-of themselves
403   // disable SROA (ext) w/o some later use that we would see and disable.
404   Value *SROAArg;
405   DenseMap<Value *, int>::iterator CostIt;
406   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
407     SROAArgValues[&I] = SROAArg;
408
409   return isInstructionFree(&I, TD);
410 }
411
412 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
413   // Propagate constants through ptrtoint.
414   if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
415     if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
416       SimplifiedValues[&I] = C;
417       return true;
418     }
419
420   // Track base/offset pairs when round-tripped through a pointer without
421   // modifications provided the integer is not too large.
422   Value *Op = I.getOperand(0);
423   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
424   if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
425     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
426     if (BaseAndOffset.first)
427       ConstantOffsetPtrs[&I] = BaseAndOffset;
428   }
429
430   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
431   Value *SROAArg;
432   DenseMap<Value *, int>::iterator CostIt;
433   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
434     SROAArgValues[&I] = SROAArg;
435
436   return isInstructionFree(&I, TD);
437 }
438
439 bool CallAnalyzer::visitCastInst(CastInst &I) {
440   // Propagate constants through ptrtoint.
441   if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
442     if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
443       SimplifiedValues[&I] = C;
444       return true;
445     }
446
447   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
448   disableSROA(I.getOperand(0));
449
450   return isInstructionFree(&I, TD);
451 }
452
453 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
454   Value *Operand = I.getOperand(0);
455   Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
456   if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
457     if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
458                                                Ops, TD)) {
459       SimplifiedValues[&I] = C;
460       return true;
461     }
462
463   // Disable any SROA on the argument to arbitrary unary operators.
464   disableSROA(Operand);
465
466   return false;
467 }
468
469 bool CallAnalyzer::visitICmp(ICmpInst &I) {
470   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
471   // First try to handle simplified comparisons.
472   if (!isa<Constant>(LHS))
473     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
474       LHS = SimpleLHS;
475   if (!isa<Constant>(RHS))
476     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
477       RHS = SimpleRHS;
478   if (Constant *CLHS = dyn_cast<Constant>(LHS))
479     if (Constant *CRHS = dyn_cast<Constant>(RHS))
480       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
481         SimplifiedValues[&I] = C;
482         return true;
483       }
484
485   // Otherwise look for a comparison between constant offset pointers with
486   // a common base.
487   Value *LHSBase, *RHSBase;
488   APInt LHSOffset, RHSOffset;
489   llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
490   if (LHSBase) {
491     llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
492     if (RHSBase && LHSBase == RHSBase) {
493       // We have common bases, fold the icmp to a constant based on the
494       // offsets.
495       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
496       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
497       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
498         SimplifiedValues[&I] = C;
499         ++NumConstantPtrCmps;
500         return true;
501       }
502     }
503   }
504
505   // If the comparison is an equality comparison with null, we can simplify it
506   // for any alloca-derived argument.
507   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
508     if (isAllocaDerivedArg(I.getOperand(0))) {
509       // We can actually predict the result of comparisons between an
510       // alloca-derived value and null. Note that this fires regardless of
511       // SROA firing.
512       bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
513       SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
514                                         : ConstantInt::getFalse(I.getType());
515       return true;
516     }
517
518   // Finally check for SROA candidates in comparisons.
519   Value *SROAArg;
520   DenseMap<Value *, int>::iterator CostIt;
521   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
522     if (isa<ConstantPointerNull>(I.getOperand(1))) {
523       accumulateSROACost(CostIt, InlineConstants::InstrCost);
524       return true;
525     }
526
527     disableSROA(CostIt);
528   }
529
530   return false;
531 }
532
533 bool CallAnalyzer::visitSub(BinaryOperator &I) {
534   // Try to handle a special case: we can fold computing the difference of two
535   // constant-related pointers.
536   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
537   Value *LHSBase, *RHSBase;
538   APInt LHSOffset, RHSOffset;
539   llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
540   if (LHSBase) {
541     llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
542     if (RHSBase && LHSBase == RHSBase) {
543       // We have common bases, fold the subtract to a constant based on the
544       // offsets.
545       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
546       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
547       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
548         SimplifiedValues[&I] = C;
549         ++NumConstantPtrDiffs;
550         return true;
551       }
552     }
553   }
554
555   // Otherwise, fall back to the generic logic for simplifying and handling
556   // instructions.
557   return Base::visitSub(I);
558 }
559
560 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
561   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
562   if (!isa<Constant>(LHS))
563     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
564       LHS = SimpleLHS;
565   if (!isa<Constant>(RHS))
566     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
567       RHS = SimpleRHS;
568   Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
569   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
570     SimplifiedValues[&I] = C;
571     return true;
572   }
573
574   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
575   disableSROA(LHS);
576   disableSROA(RHS);
577
578   return false;
579 }
580
581 bool CallAnalyzer::visitLoad(LoadInst &I) {
582   Value *SROAArg;
583   DenseMap<Value *, int>::iterator CostIt;
584   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
585     if (I.isSimple()) {
586       accumulateSROACost(CostIt, InlineConstants::InstrCost);
587       return true;
588     }
589
590     disableSROA(CostIt);
591   }
592
593   return false;
594 }
595
596 bool CallAnalyzer::visitStore(StoreInst &I) {
597   Value *SROAArg;
598   DenseMap<Value *, int>::iterator CostIt;
599   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
600     if (I.isSimple()) {
601       accumulateSROACost(CostIt, InlineConstants::InstrCost);
602       return true;
603     }
604
605     disableSROA(CostIt);
606   }
607
608   return false;
609 }
610
611 bool CallAnalyzer::visitCallSite(CallSite CS) {
612   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
613       !F.getFnAttributes().hasAttribute(Attributes::ReturnsTwice)) {
614     // This aborts the entire analysis.
615     ExposesReturnsTwice = true;
616     return false;
617   }
618
619   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
620     switch (II->getIntrinsicID()) {
621     default:
622       return Base::visitCallSite(CS);
623
624     case Intrinsic::memset:
625     case Intrinsic::memcpy:
626     case Intrinsic::memmove:
627       // SROA can usually chew through these intrinsics, but they aren't free.
628       return false;
629     }
630   }
631
632   if (Function *F = CS.getCalledFunction()) {
633     if (F == CS.getInstruction()->getParent()->getParent()) {
634       // This flag will fully abort the analysis, so don't bother with anything
635       // else.
636       IsRecursiveCall = true;
637       return false;
638     }
639
640     if (!callIsSmall(CS)) {
641       // We account for the average 1 instruction per call argument setup
642       // here.
643       Cost += CS.arg_size() * InlineConstants::InstrCost;
644
645       // Everything other than inline ASM will also have a significant cost
646       // merely from making the call.
647       if (!isa<InlineAsm>(CS.getCalledValue()))
648         Cost += InlineConstants::CallPenalty;
649     }
650
651     return Base::visitCallSite(CS);
652   }
653
654   // Otherwise we're in a very special case -- an indirect function call. See
655   // if we can be particularly clever about this.
656   Value *Callee = CS.getCalledValue();
657
658   // First, pay the price of the argument setup. We account for the average
659   // 1 instruction per call argument setup here.
660   Cost += CS.arg_size() * InlineConstants::InstrCost;
661
662   // Next, check if this happens to be an indirect function call to a known
663   // function in this inline context. If not, we've done all we can.
664   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
665   if (!F)
666     return Base::visitCallSite(CS);
667
668   // If we have a constant that we are calling as a function, we can peer
669   // through it and see the function target. This happens not infrequently
670   // during devirtualization and so we want to give it a hefty bonus for
671   // inlining, but cap that bonus in the event that inlining wouldn't pan
672   // out. Pretend to inline the function, with a custom threshold.
673   CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
674   if (CA.analyzeCall(CS)) {
675     // We were able to inline the indirect call! Subtract the cost from the
676     // bonus we want to apply, but don't go below zero.
677     Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
678   }
679
680   return Base::visitCallSite(CS);
681 }
682
683 bool CallAnalyzer::visitInstruction(Instruction &I) {
684   // Some instructions are free. All of the free intrinsics can also be
685   // handled by SROA, etc.
686   if (isInstructionFree(&I, TD))
687     return true;
688
689   // We found something we don't understand or can't handle. Mark any SROA-able
690   // values in the operand list as no longer viable.
691   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
692     disableSROA(*OI);
693
694   return false;
695 }
696
697
698 /// \brief Analyze a basic block for its contribution to the inline cost.
699 ///
700 /// This method walks the analyzer over every instruction in the given basic
701 /// block and accounts for their cost during inlining at this callsite. It
702 /// aborts early if the threshold has been exceeded or an impossible to inline
703 /// construct has been detected. It returns false if inlining is no longer
704 /// viable, and true if inlining remains viable.
705 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
706   for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
707        I != E; ++I) {
708     ++NumInstructions;
709     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
710       ++NumVectorInstructions;
711
712     // If the instruction simplified to a constant, there is no cost to this
713     // instruction. Visit the instructions using our InstVisitor to account for
714     // all of the per-instruction logic. The visit tree returns true if we
715     // consumed the instruction in any way, and false if the instruction's base
716     // cost should count against inlining.
717     if (Base::visit(I))
718       ++NumInstructionsSimplified;
719     else
720       Cost += InlineConstants::InstrCost;
721
722     // If the visit this instruction detected an uninlinable pattern, abort.
723     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
724       return false;
725
726     // If the caller is a recursive function then we don't want to inline
727     // functions which allocate a lot of stack space because it would increase
728     // the caller stack usage dramatically.
729     if (IsCallerRecursive &&
730         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
731       return false;
732
733     if (NumVectorInstructions > NumInstructions/2)
734       VectorBonus = FiftyPercentVectorBonus;
735     else if (NumVectorInstructions > NumInstructions/10)
736       VectorBonus = TenPercentVectorBonus;
737     else
738       VectorBonus = 0;
739
740     // Check if we've past the threshold so we don't spin in huge basic
741     // blocks that will never inline.
742     if (Cost > (Threshold + VectorBonus))
743       return false;
744   }
745
746   return true;
747 }
748
749 /// \brief Compute the base pointer and cumulative constant offsets for V.
750 ///
751 /// This strips all constant offsets off of V, leaving it the base pointer, and
752 /// accumulates the total constant offset applied in the returned constant. It
753 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
754 /// no constant offsets applied.
755 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
756   if (!TD || !V->getType()->isPointerTy())
757     return 0;
758
759   unsigned IntPtrWidth = TD->getPointerSizeInBits();
760   APInt Offset = APInt::getNullValue(IntPtrWidth);
761
762   // Even though we don't look through PHI nodes, we could be called on an
763   // instruction in an unreachable block, which may be on a cycle.
764   SmallPtrSet<Value *, 4> Visited;
765   Visited.insert(V);
766   do {
767     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
768       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
769         return 0;
770       V = GEP->getPointerOperand();
771     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
772       V = cast<Operator>(V)->getOperand(0);
773     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
774       if (GA->mayBeOverridden())
775         break;
776       V = GA->getAliasee();
777     } else {
778       break;
779     }
780     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
781   } while (Visited.insert(V));
782
783   Type *IntPtrTy = TD->getIntPtrType(V->getContext());
784   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
785 }
786
787 /// \brief Analyze a call site for potential inlining.
788 ///
789 /// Returns true if inlining this call is viable, and false if it is not
790 /// viable. It computes the cost and adjusts the threshold based on numerous
791 /// factors and heuristics. If this method returns false but the computed cost
792 /// is below the computed threshold, then inlining was forcibly disabled by
793 /// some artifact of the routine.
794 bool CallAnalyzer::analyzeCall(CallSite CS) {
795   ++NumCallsAnalyzed;
796
797   // Track whether the post-inlining function would have more than one basic
798   // block. A single basic block is often intended for inlining. Balloon the
799   // threshold by 50% until we pass the single-BB phase.
800   bool SingleBB = true;
801   int SingleBBBonus = Threshold / 2;
802   Threshold += SingleBBBonus;
803
804   // Perform some tweaks to the cost and threshold based on the direct
805   // callsite information.
806
807   // We want to more aggressively inline vector-dense kernels, so up the
808   // threshold, and we'll lower it if the % of vector instructions gets too
809   // low.
810   assert(NumInstructions == 0);
811   assert(NumVectorInstructions == 0);
812   FiftyPercentVectorBonus = Threshold;
813   TenPercentVectorBonus = Threshold / 2;
814
815   // Give out bonuses per argument, as the instructions setting them up will
816   // be gone after inlining.
817   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
818     if (TD && CS.isByValArgument(I)) {
819       // We approximate the number of loads and stores needed by dividing the
820       // size of the byval type by the target's pointer size.
821       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
822       unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
823       unsigned PointerSize = TD->getPointerSizeInBits();
824       // Ceiling division.
825       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
826
827       // If it generates more than 8 stores it is likely to be expanded as an
828       // inline memcpy so we take that as an upper bound. Otherwise we assume
829       // one load and one store per word copied.
830       // FIXME: The maxStoresPerMemcpy setting from the target should be used
831       // here instead of a magic number of 8, but it's not available via
832       // DataLayout.
833       NumStores = std::min(NumStores, 8U);
834
835       Cost -= 2 * NumStores * InlineConstants::InstrCost;
836     } else {
837       // For non-byval arguments subtract off one instruction per call
838       // argument.
839       Cost -= InlineConstants::InstrCost;
840     }
841   }
842
843   // If there is only one call of the function, and it has internal linkage,
844   // the cost of inlining it drops dramatically.
845   if (F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction())
846     Cost += InlineConstants::LastCallToStaticBonus;
847
848   // If the instruction after the call, or if the normal destination of the
849   // invoke is an unreachable instruction, the function is noreturn. As such,
850   // there is little point in inlining this unless there is literally zero
851   // cost.
852   Instruction *Instr = CS.getInstruction();
853   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
854     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
855       Threshold = 1;
856   } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
857     Threshold = 1;
858
859   // If this function uses the coldcc calling convention, prefer not to inline
860   // it.
861   if (F.getCallingConv() == CallingConv::Cold)
862     Cost += InlineConstants::ColdccPenalty;
863
864   // Check if we're done. This can happen due to bonuses and penalties.
865   if (Cost > Threshold)
866     return false;
867
868   if (F.empty())
869     return true;
870
871   Function *Caller = CS.getInstruction()->getParent()->getParent();
872   // Check if the caller function is recursive itself.
873   for (Value::use_iterator U = Caller->use_begin(), E = Caller->use_end();
874        U != E; ++U) {
875     CallSite Site(cast<Value>(*U));
876     if (!Site)
877       continue;
878     Instruction *I = Site.getInstruction();
879     if (I->getParent()->getParent() == Caller) {
880       IsCallerRecursive = true;
881       break;
882     }
883   }
884
885   // Track whether we've seen a return instruction. The first return
886   // instruction is free, as at least one will usually disappear in inlining.
887   bool HasReturn = false;
888
889   // Populate our simplified values by mapping from function arguments to call
890   // arguments with known important simplifications.
891   CallSite::arg_iterator CAI = CS.arg_begin();
892   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
893        FAI != FAE; ++FAI, ++CAI) {
894     assert(CAI != CS.arg_end());
895     if (Constant *C = dyn_cast<Constant>(CAI))
896       SimplifiedValues[FAI] = C;
897
898     Value *PtrArg = *CAI;
899     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
900       ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
901
902       // We can SROA any pointer arguments derived from alloca instructions.
903       if (isa<AllocaInst>(PtrArg)) {
904         SROAArgValues[FAI] = PtrArg;
905         SROAArgCosts[PtrArg] = 0;
906       }
907     }
908   }
909   NumConstantArgs = SimplifiedValues.size();
910   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
911   NumAllocaArgs = SROAArgValues.size();
912
913   // The worklist of live basic blocks in the callee *after* inlining. We avoid
914   // adding basic blocks of the callee which can be proven to be dead for this
915   // particular call site in order to get more accurate cost estimates. This
916   // requires a somewhat heavyweight iteration pattern: we need to walk the
917   // basic blocks in a breadth-first order as we insert live successors. To
918   // accomplish this, prioritizing for small iterations because we exit after
919   // crossing our threshold, we use a small-size optimized SetVector.
920   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
921                                   SmallPtrSet<BasicBlock *, 16> > BBSetVector;
922   BBSetVector BBWorklist;
923   BBWorklist.insert(&F.getEntryBlock());
924   // Note that we *must not* cache the size, this loop grows the worklist.
925   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
926     // Bail out the moment we cross the threshold. This means we'll under-count
927     // the cost, but only when undercounting doesn't matter.
928     if (Cost > (Threshold + VectorBonus))
929       break;
930
931     BasicBlock *BB = BBWorklist[Idx];
932     if (BB->empty())
933       continue;
934
935     // Handle the terminator cost here where we can track returns and other
936     // function-wide constructs.
937     TerminatorInst *TI = BB->getTerminator();
938
939     // We never want to inline functions that contain an indirectbr.  This is
940     // incorrect because all the blockaddress's (in static global initializers
941     // for example) would be referring to the original function, and this
942     // indirect jump would jump from the inlined copy of the function into the 
943     // original function which is extremely undefined behavior.
944     // FIXME: This logic isn't really right; we can safely inline functions
945     // with indirectbr's as long as no other function or global references the
946     // blockaddress of a block within the current function.  And as a QOI issue,
947     // if someone is using a blockaddress without an indirectbr, and that
948     // reference somehow ends up in another function or global, we probably
949     // don't want to inline this function.
950     if (isa<IndirectBrInst>(TI))
951       return false;
952
953     if (!HasReturn && isa<ReturnInst>(TI))
954       HasReturn = true;
955     else
956       Cost += InlineConstants::InstrCost;
957
958     // Analyze the cost of this block. If we blow through the threshold, this
959     // returns false, and we can bail on out.
960     if (!analyzeBlock(BB)) {
961       if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca)
962         return false;
963
964       // If the caller is a recursive function then we don't want to inline
965       // functions which allocate a lot of stack space because it would increase
966       // the caller stack usage dramatically.
967       if (IsCallerRecursive &&
968           AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
969         return false;
970
971       break;
972     }
973
974     // Add in the live successors by first checking whether we have terminator
975     // that may be simplified based on the values simplified by this call.
976     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
977       if (BI->isConditional()) {
978         Value *Cond = BI->getCondition();
979         if (ConstantInt *SimpleCond
980               = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
981           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
982           continue;
983         }
984       }
985     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
986       Value *Cond = SI->getCondition();
987       if (ConstantInt *SimpleCond
988             = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
989         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
990         continue;
991       }
992     }
993
994     // If we're unable to select a particular successor, just count all of
995     // them.
996     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
997          ++TIdx)
998       BBWorklist.insert(TI->getSuccessor(TIdx));
999
1000     // If we had any successors at this point, than post-inlining is likely to
1001     // have them as well. Note that we assume any basic blocks which existed
1002     // due to branches or switches which folded above will also fold after
1003     // inlining.
1004     if (SingleBB && TI->getNumSuccessors() > 1) {
1005       // Take off the bonus we applied to the threshold.
1006       Threshold -= SingleBBBonus;
1007       SingleBB = false;
1008     }
1009   }
1010
1011   Threshold += VectorBonus;
1012
1013   return Cost < Threshold;
1014 }
1015
1016 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1017 /// \brief Dump stats about this call's analysis.
1018 void CallAnalyzer::dump() {
1019 #define DEBUG_PRINT_STAT(x) llvm::dbgs() << "      " #x ": " << x << "\n"
1020   DEBUG_PRINT_STAT(NumConstantArgs);
1021   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1022   DEBUG_PRINT_STAT(NumAllocaArgs);
1023   DEBUG_PRINT_STAT(NumConstantPtrCmps);
1024   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1025   DEBUG_PRINT_STAT(NumInstructionsSimplified);
1026   DEBUG_PRINT_STAT(SROACostSavings);
1027   DEBUG_PRINT_STAT(SROACostSavingsLost);
1028 #undef DEBUG_PRINT_STAT
1029 }
1030 #endif
1031
1032 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
1033   return getInlineCost(CS, CS.getCalledFunction(), Threshold);
1034 }
1035
1036 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
1037                                              int Threshold) {
1038   // Cannot inline indirect calls.
1039   if (!Callee)
1040     return llvm::InlineCost::getNever();
1041
1042   // Calls to functions with always-inline attributes should be inlined
1043   // whenever possible.
1044   if (Callee->getFnAttributes().hasAttribute(Attributes::AlwaysInline)) {
1045     if (isInlineViable(*Callee))
1046       return llvm::InlineCost::getAlways();
1047     return llvm::InlineCost::getNever();
1048   }
1049
1050   // Don't inline functions which can be redefined at link-time to mean
1051   // something else.  Don't inline functions marked noinline or call sites
1052   // marked noinline.
1053   if (Callee->mayBeOverridden() ||
1054       Callee->getFnAttributes().hasAttribute(Attributes::NoInline) ||
1055       CS.isNoInline())
1056     return llvm::InlineCost::getNever();
1057
1058   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
1059         << "...\n");
1060
1061   CallAnalyzer CA(TD, *Callee, Threshold);
1062   bool ShouldInline = CA.analyzeCall(CS);
1063
1064   DEBUG(CA.dump());
1065
1066   // Check if there was a reason to force inlining or no inlining.
1067   if (!ShouldInline && CA.getCost() < CA.getThreshold())
1068     return InlineCost::getNever();
1069   if (ShouldInline && CA.getCost() >= CA.getThreshold())
1070     return InlineCost::getAlways();
1071
1072   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1073 }
1074
1075 bool InlineCostAnalyzer::isInlineViable(Function &F) {
1076   bool ReturnsTwice =F.getFnAttributes().hasAttribute(Attributes::ReturnsTwice);
1077   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1078     // Disallow inlining of functions which contain an indirect branch.
1079     if (isa<IndirectBrInst>(BI->getTerminator()))
1080       return false;
1081
1082     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
1083          ++II) {
1084       CallSite CS(II);
1085       if (!CS)
1086         continue;
1087
1088       // Disallow recursive calls.
1089       if (&F == CS.getCalledFunction())
1090         return false;
1091
1092       // Disallow calls which expose returns-twice to a function not previously
1093       // attributed as such.
1094       if (!ReturnsTwice && CS.isCall() &&
1095           cast<CallInst>(CS.getInstruction())->canReturnTwice())
1096         return false;
1097     }
1098   }
1099
1100   return true;
1101 }