LLVM  6.0.0svn
PartiallyInlineLibCalls.cpp
Go to the documentation of this file.
1 //===--- PartiallyInlineLibCalls.cpp - Partially inline libcalls ----------===//
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 pass tries to partially inline the fast path of well-known library
11 // functions, such as using square-root instructions for cases where sqrt()
12 // does not need to set errno.
13 //
14 //===----------------------------------------------------------------------===//
15 
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/Transforms/Scalar.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "partially-inline-libcalls"
26 
27 
28 static bool optimizeSQRT(CallInst *Call, Function *CalledFunc,
29  BasicBlock &CurrBB, Function::iterator &BB) {
30  // There is no need to change the IR, since backend will emit sqrt
31  // instruction if the call has already been marked read-only.
32  if (Call->onlyReadsMemory())
33  return false;
34 
35  // Do the following transformation:
36  //
37  // (before)
38  // dst = sqrt(src)
39  //
40  // (after)
41  // v0 = sqrt_noreadmem(src) # native sqrt instruction.
42  // if (v0 is a NaN)
43  // v1 = sqrt(src) # library call.
44  // dst = phi(v0, v1)
45  //
46 
47  // Move all instructions following Call to newly created block JoinBB.
48  // Create phi and replace all uses.
49  BasicBlock *JoinBB = llvm::SplitBlock(&CurrBB, Call->getNextNode());
50  IRBuilder<> Builder(JoinBB, JoinBB->begin());
51  PHINode *Phi = Builder.CreatePHI(Call->getType(), 2);
52  Call->replaceAllUsesWith(Phi);
53 
54  // Create basic block LibCallBB and insert a call to library function sqrt.
55  BasicBlock *LibCallBB = BasicBlock::Create(CurrBB.getContext(), "call.sqrt",
56  CurrBB.getParent(), JoinBB);
57  Builder.SetInsertPoint(LibCallBB);
58  Instruction *LibCall = Call->clone();
59  Builder.Insert(LibCall);
60  Builder.CreateBr(JoinBB);
61 
62  // Add attribute "readnone" so that backend can use a native sqrt instruction
63  // for this call. Insert a FP compare instruction and a conditional branch
64  // at the end of CurrBB.
65  Call->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
66  CurrBB.getTerminator()->eraseFromParent();
67  Builder.SetInsertPoint(&CurrBB);
68  Value *FCmp = Builder.CreateFCmpOEQ(Call, Call);
69  Builder.CreateCondBr(FCmp, JoinBB, LibCallBB);
70 
71  // Add phi operands.
72  Phi->addIncoming(Call, &CurrBB);
73  Phi->addIncoming(LibCall, LibCallBB);
74 
75  BB = JoinBB->getIterator();
76  return true;
77 }
78 
80  const TargetTransformInfo *TTI) {
81  bool Changed = false;
82 
83  Function::iterator CurrBB;
84  for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE;) {
85  CurrBB = BB++;
86 
87  for (BasicBlock::iterator II = CurrBB->begin(), IE = CurrBB->end();
88  II != IE; ++II) {
89  CallInst *Call = dyn_cast<CallInst>(&*II);
90  Function *CalledFunc;
91 
92  if (!Call || !(CalledFunc = Call->getCalledFunction()))
93  continue;
94 
95  if (Call->isNoBuiltin())
96  continue;
97 
98  // Skip if function either has local linkage or is not a known library
99  // function.
100  LibFunc LF;
101  if (CalledFunc->hasLocalLinkage() ||
102  !TLI->getLibFunc(*CalledFunc, LF) || !TLI->has(LF))
103  continue;
104 
105  switch (LF) {
106  case LibFunc_sqrtf:
107  case LibFunc_sqrt:
108  if (TTI->haveFastSqrt(Call->getType()) &&
109  optimizeSQRT(Call, CalledFunc, *CurrBB, BB))
110  break;
111  continue;
112  default:
113  continue;
114  }
115 
116  Changed = true;
117  break;
118  }
119  }
120 
121  return Changed;
122 }
123 
126  auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
127  auto &TTI = AM.getResult<TargetIRAnalysis>(F);
128  if (!runPartiallyInlineLibCalls(F, &TLI, &TTI))
129  return PreservedAnalyses::all();
130  return PreservedAnalyses::none();
131 }
132 
133 namespace {
134 class PartiallyInlineLibCallsLegacyPass : public FunctionPass {
135 public:
136  static char ID;
137 
138  PartiallyInlineLibCallsLegacyPass() : FunctionPass(ID) {
141  }
142 
143  void getAnalysisUsage(AnalysisUsage &AU) const override {
147  }
148 
149  bool runOnFunction(Function &F) override {
150  if (skipFunction(F))
151  return false;
152 
153  TargetLibraryInfo *TLI =
154  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
155  const TargetTransformInfo *TTI =
156  &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
157  return runPartiallyInlineLibCalls(F, TLI, TTI);
158  }
159 };
160 }
161 
163 INITIALIZE_PASS_BEGIN(PartiallyInlineLibCallsLegacyPass,
164  "partially-inline-libcalls",
165  "Partially inline calls to library functions", false,
166  false)
169 INITIALIZE_PASS_END(PartiallyInlineLibCallsLegacyPass,
170  "partially-inline-libcalls",
171  "Partially inline calls to library functions", false, false)
172 
174  return new PartiallyInlineLibCallsLegacyPass();
175 }
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:69
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
iterator end()
Definition: Function.h:590
This class represents a function call, abstracting a target machine&#39;s calling convention.
Analysis pass providing the TargetTransformInfo.
F(f)
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:33
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:668
INITIALIZE_PASS_BEGIN(PartiallyInlineLibCallsLegacyPass, "partially-inline-libcalls", "Partially inline calls to library functions", false, false) INITIALIZE_PASS_END(PartiallyInlineLibCallsLegacyPass
FunctionPass * createPartiallyInlineLibCallsPass()
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:91
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool has(LibFunc F) const
Tests whether a library function is available.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
iterator begin()
Definition: Function.h:588
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
static bool runOnFunction(Function &F, bool PostInlining)
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
static bool runPartiallyInlineLibCalls(Function &F, TargetLibraryInfo *TLI, const TargetTransformInfo *TTI)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:101
self_iterator getIterator()
Definition: ilist_node.h:82
bool haveFastSqrt(Type *Ty) const
Return true if the hardware has a fast square-root instruction.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
static bool optimizeSQRT(CallInst *Call, Function *CalledFunc, BasicBlock &CurrBB, Function::iterator &BB)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Iterator for intrusive lists based on ilist_node.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Analysis pass providing the TargetLibraryInfo.
LLVM Value Representation.
Definition: Value.h:73
A container for analyses that lazily runs them and caches their results.
void addAttribute(unsigned i, Attribute::AttrKind Kind)
adds the attribute to the list of attributes.
This pass exposes codegen information to IR-level passes.
void initializePartiallyInlineLibCallsLegacyPassPass(PassRegistry &)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120