1 //===- FunctionPropertiesAnalysis.cpp - Function Properties Analysis ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the FunctionPropertiesInfo and FunctionPropertiesAnalysis
10 // classes used to extract function properties.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/FunctionPropertiesAnalysis.h"
15 #include "llvm/IR/Instructions.h"
16 
17 using namespace llvm;
18 
19 FunctionPropertiesInfo
20 FunctionPropertiesInfo::getFunctionPropertiesInfo(const Function &F) {
21 
22   FunctionPropertiesInfo FPI;
23 
24   FPI.Uses = ((!F.hasLocalLinkage()) ? 1 : 0) + F.getNumUses();
25 
26   for (const auto &BB : F) {
27     ++FPI.BasicBlockCount;
28 
29     if (const auto *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
30       if (BI->isConditional())
31         FPI.BlocksReachedFromConditionalInstruction += BI->getNumSuccessors();
32     } else if (const auto *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
33       FPI.BlocksReachedFromConditionalInstruction +=
34           (SI->getNumCases() + (nullptr != SI->getDefaultDest()));
35     }
36 
37     for (const auto &I : BB) {
38       if (auto *CS = dyn_cast<CallBase>(&I)) {
39         const auto *Callee = CS->getCalledFunction();
40         if (Callee && !Callee->isIntrinsic() && !Callee->isDeclaration())
41           ++FPI.DirectCallsToDefinedFunctions;
42       }
43     }
44   }
45   return FPI;
46 }
47 
48 void FunctionPropertiesInfo::print(raw_ostream &OS) const {
49   OS << "BasicBlockCount: " << BasicBlockCount << "\n"
50      << "BlocksReachedFromConditionalInstruction: "
51      << BlocksReachedFromConditionalInstruction << "\n"
52      << "Uses: " << Uses << "\n"
53      << "DirectCallsToDefinedFunctions: " << DirectCallsToDefinedFunctions
54      << "\n\n";
55 }
56 
57 AnalysisKey FunctionPropertiesAnalysis::Key;
58 
59 FunctionPropertiesInfo
60 FunctionPropertiesAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
61   return FunctionPropertiesInfo::getFunctionPropertiesInfo(F);
62 }
63 
64 PreservedAnalyses
65 FunctionPropertiesPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
66   OS << "Printing analysis results of CFA for function "
67      << "'" << F.getName() << "':"
68      << "\n";
69   AM.getResult<FunctionPropertiesAnalysis>(F).print(OS);
70   return PreservedAnalyses::all();
71 }