180814287SRaphael Isemann //===-- Function.cpp ------------------------------------------------------===//
230fdc8d8SChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
630fdc8d8SChris Lattner //
730fdc8d8SChris Lattner //===----------------------------------------------------------------------===//
830fdc8d8SChris Lattner 
930fdc8d8SChris Lattner #include "lldb/Symbol/Function.h"
1068793919SJonas Devlieghere #include "lldb/Core/Debugger.h"
1144d93782SGreg Clayton #include "lldb/Core/Disassembler.h"
1230fdc8d8SChris Lattner #include "lldb/Core/Module.h"
134b36f791SVedant Kumar #include "lldb/Core/ModuleList.h"
1430fdc8d8SChris Lattner #include "lldb/Core/Section.h"
15e38a5eddSGreg Clayton #include "lldb/Host/Host.h"
1630fdc8d8SChris Lattner #include "lldb/Symbol/CompileUnit.h"
17b9c1b51eSKate Stone #include "lldb/Symbol/CompilerType.h"
1830fdc8d8SChris Lattner #include "lldb/Symbol/LineTable.h"
1972e4940bSSean Callanan #include "lldb/Symbol/SymbolFile.h"
206754e04fSEnrico Granata #include "lldb/Target/Language.h"
214fdbc072SVedant Kumar #include "lldb/Target/Target.h"
22c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
234b36f791SVedant Kumar #include "lldb/Utility/Log.h"
24cc427fadSSean Callanan #include "llvm/Support/Casting.h"
2530fdc8d8SChris Lattner 
26c9800667SGreg Clayton using namespace lldb;
2730fdc8d8SChris Lattner using namespace lldb_private;
2830fdc8d8SChris Lattner 
2905097246SAdrian Prantl // Basic function information is contained in the FunctionInfo class. It is
3005097246SAdrian Prantl // designed to contain the name, linkage name, and declaration location.
FunctionInfo(const char * name,const Declaration * decl_ptr)31b9c1b51eSKate Stone FunctionInfo::FunctionInfo(const char *name, const Declaration *decl_ptr)
32b9c1b51eSKate Stone     : m_name(name), m_declaration(decl_ptr) {}
3330fdc8d8SChris Lattner 
FunctionInfo(ConstString name,const Declaration * decl_ptr)340e4c4821SAdrian Prantl FunctionInfo::FunctionInfo(ConstString name, const Declaration *decl_ptr)
35b9c1b51eSKate Stone     : m_name(name), m_declaration(decl_ptr) {}
3630fdc8d8SChris Lattner 
37fd2433e1SJonas Devlieghere FunctionInfo::~FunctionInfo() = default;
3830fdc8d8SChris Lattner 
Dump(Stream * s,bool show_fullpaths) const39b9c1b51eSKate Stone void FunctionInfo::Dump(Stream *s, bool show_fullpaths) const {
4030fdc8d8SChris Lattner   if (m_name)
4130fdc8d8SChris Lattner     *s << ", name = \"" << m_name << "\"";
426dbd3983SGreg Clayton   m_declaration.Dump(s, show_fullpaths);
4330fdc8d8SChris Lattner }
4430fdc8d8SChris Lattner 
Compare(const FunctionInfo & a,const FunctionInfo & b)45b9c1b51eSKate Stone int FunctionInfo::Compare(const FunctionInfo &a, const FunctionInfo &b) {
4630fdc8d8SChris Lattner   int result = ConstString::Compare(a.GetName(), b.GetName());
4730fdc8d8SChris Lattner   if (result)
4830fdc8d8SChris Lattner     return result;
4930fdc8d8SChris Lattner 
5030fdc8d8SChris Lattner   return Declaration::Compare(a.m_declaration, b.m_declaration);
5130fdc8d8SChris Lattner }
5230fdc8d8SChris Lattner 
GetDeclaration()53b9c1b51eSKate Stone Declaration &FunctionInfo::GetDeclaration() { return m_declaration; }
5430fdc8d8SChris Lattner 
GetDeclaration() const55b9c1b51eSKate Stone const Declaration &FunctionInfo::GetDeclaration() const {
5630fdc8d8SChris Lattner   return m_declaration;
5730fdc8d8SChris Lattner }
5830fdc8d8SChris Lattner 
GetName() const59b9c1b51eSKate Stone ConstString FunctionInfo::GetName() const { return m_name; }
6030fdc8d8SChris Lattner 
MemorySize() const61b9c1b51eSKate Stone size_t FunctionInfo::MemorySize() const {
6230fdc8d8SChris Lattner   return m_name.MemorySize() + m_declaration.MemorySize();
6330fdc8d8SChris Lattner }
6430fdc8d8SChris Lattner 
InlineFunctionInfo(const char * name,llvm::StringRef mangled,const Declaration * decl_ptr,const Declaration * call_decl_ptr)65939411c1SAdrian Prantl InlineFunctionInfo::InlineFunctionInfo(const char *name,
66939411c1SAdrian Prantl                                        llvm::StringRef mangled,
6730fdc8d8SChris Lattner                                        const Declaration *decl_ptr,
68b9c1b51eSKate Stone                                        const Declaration *call_decl_ptr)
69939411c1SAdrian Prantl     : FunctionInfo(name, decl_ptr), m_mangled(mangled),
70b9c1b51eSKate Stone       m_call_decl(call_decl_ptr) {}
7130fdc8d8SChris Lattner 
InlineFunctionInfo(ConstString name,const Mangled & mangled,const Declaration * decl_ptr,const Declaration * call_decl_ptr)720e4c4821SAdrian Prantl InlineFunctionInfo::InlineFunctionInfo(ConstString name,
7330fdc8d8SChris Lattner                                        const Mangled &mangled,
7430fdc8d8SChris Lattner                                        const Declaration *decl_ptr,
75b9c1b51eSKate Stone                                        const Declaration *call_decl_ptr)
76b9c1b51eSKate Stone     : FunctionInfo(name, decl_ptr), m_mangled(mangled),
77b9c1b51eSKate Stone       m_call_decl(call_decl_ptr) {}
7830fdc8d8SChris Lattner 
79fd2433e1SJonas Devlieghere InlineFunctionInfo::~InlineFunctionInfo() = default;
8030fdc8d8SChris Lattner 
Dump(Stream * s,bool show_fullpaths) const81b9c1b51eSKate Stone void InlineFunctionInfo::Dump(Stream *s, bool show_fullpaths) const {
826dbd3983SGreg Clayton   FunctionInfo::Dump(s, show_fullpaths);
8330fdc8d8SChris Lattner   if (m_mangled)
8430fdc8d8SChris Lattner     m_mangled.Dump(s);
8530fdc8d8SChris Lattner }
8630fdc8d8SChris Lattner 
DumpStopContext(Stream * s) const8722b04487SAlex Langford void InlineFunctionInfo::DumpStopContext(Stream *s) const {
8830fdc8d8SChris Lattner   //    s->Indent("[inlined] ");
8930fdc8d8SChris Lattner   s->Indent();
9030fdc8d8SChris Lattner   if (m_mangled)
9122b04487SAlex Langford     s->PutCString(m_mangled.GetName().AsCString());
9230fdc8d8SChris Lattner   else
9330fdc8d8SChris Lattner     s->PutCString(m_name.AsCString());
9430fdc8d8SChris Lattner }
9530fdc8d8SChris Lattner 
GetName() const9622b04487SAlex Langford ConstString InlineFunctionInfo::GetName() const {
971b72fcb7SGreg Clayton   if (m_mangled)
9822b04487SAlex Langford     return m_mangled.GetName();
991b72fcb7SGreg Clayton   return m_name;
1001b72fcb7SGreg Clayton }
1011b72fcb7SGreg Clayton 
GetDisplayName() const10222b04487SAlex Langford ConstString InlineFunctionInfo::GetDisplayName() const {
103c1f705c2SEnrico Granata   if (m_mangled)
10422b04487SAlex Langford     return m_mangled.GetDisplayDemangledName();
105c1f705c2SEnrico Granata   return m_name;
106c1f705c2SEnrico Granata }
1071b72fcb7SGreg Clayton 
GetCallSite()108b9c1b51eSKate Stone Declaration &InlineFunctionInfo::GetCallSite() { return m_call_decl; }
109b9c1b51eSKate Stone 
GetCallSite() const110b9c1b51eSKate Stone const Declaration &InlineFunctionInfo::GetCallSite() const {
11130fdc8d8SChris Lattner   return m_call_decl;
11230fdc8d8SChris Lattner }
11330fdc8d8SChris Lattner 
GetMangled()114b9c1b51eSKate Stone Mangled &InlineFunctionInfo::GetMangled() { return m_mangled; }
11530fdc8d8SChris Lattner 
GetMangled() const116b9c1b51eSKate Stone const Mangled &InlineFunctionInfo::GetMangled() const { return m_mangled; }
11730fdc8d8SChris Lattner 
MemorySize() const118b9c1b51eSKate Stone size_t InlineFunctionInfo::MemorySize() const {
11930fdc8d8SChris Lattner   return FunctionInfo::MemorySize() + m_mangled.MemorySize();
12030fdc8d8SChris Lattner }
12130fdc8d8SChris Lattner 
1224fdbc072SVedant Kumar /// @name Call site related structures
1234fdbc072SVedant Kumar /// @{
1244fdbc072SVedant Kumar 
GetLoadAddress(lldb::addr_t unresolved_pc,Function & caller,Target & target)12503e29e2cSVedant Kumar lldb::addr_t CallEdge::GetLoadAddress(lldb::addr_t unresolved_pc,
12603e29e2cSVedant Kumar                                       Function &caller, Target &target) {
127a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Step);
128f0120556SVedant Kumar 
129f0120556SVedant Kumar   const Address &caller_start_addr = caller.GetAddressRange().GetBaseAddress();
130f0120556SVedant Kumar 
131f0120556SVedant Kumar   ModuleSP caller_module_sp = caller_start_addr.GetModule();
132f0120556SVedant Kumar   if (!caller_module_sp) {
13303e29e2cSVedant Kumar     LLDB_LOG(log, "GetLoadAddress: cannot get Module for caller");
134f0120556SVedant Kumar     return LLDB_INVALID_ADDRESS;
135f0120556SVedant Kumar   }
136f0120556SVedant Kumar 
137f0120556SVedant Kumar   SectionList *section_list = caller_module_sp->GetSectionList();
138f0120556SVedant Kumar   if (!section_list) {
13903e29e2cSVedant Kumar     LLDB_LOG(log, "GetLoadAddress: cannot get SectionList for Module");
140f0120556SVedant Kumar     return LLDB_INVALID_ADDRESS;
141f0120556SVedant Kumar   }
142f0120556SVedant Kumar 
14303e29e2cSVedant Kumar   Address the_addr = Address(unresolved_pc, section_list);
14403e29e2cSVedant Kumar   lldb::addr_t load_addr = the_addr.GetLoadAddress(&target);
14503e29e2cSVedant Kumar   return load_addr;
14603e29e2cSVedant Kumar }
14703e29e2cSVedant Kumar 
GetReturnPCAddress(Function & caller,Target & target) const14803e29e2cSVedant Kumar lldb::addr_t CallEdge::GetReturnPCAddress(Function &caller,
14903e29e2cSVedant Kumar                                           Target &target) const {
1500081149fSPavel Labath   return GetLoadAddress(GetUnresolvedReturnPCAddress(), caller, target);
1514b36f791SVedant Kumar }
1524b36f791SVedant Kumar 
ParseSymbolFileAndResolve(ModuleList & images)1534fdbc072SVedant Kumar void DirectCallEdge::ParseSymbolFileAndResolve(ModuleList &images) {
1544b36f791SVedant Kumar   if (resolved)
1554b36f791SVedant Kumar     return;
1564b36f791SVedant Kumar 
157a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Step);
1584fdbc072SVedant Kumar   LLDB_LOG(log, "DirectCallEdge: Lazily parsing the call graph for {0}",
1594b36f791SVedant Kumar            lazy_callee.symbol_name);
1604b36f791SVedant Kumar 
1614b36f791SVedant Kumar   auto resolve_lazy_callee = [&]() -> Function * {
1624b36f791SVedant Kumar     ConstString callee_name{lazy_callee.symbol_name};
1634b36f791SVedant Kumar     SymbolContextList sc_list;
1644b36f791SVedant Kumar     images.FindFunctionSymbols(callee_name, eFunctionNameTypeAuto, sc_list);
1651ad655e2SAdrian Prantl     size_t num_matches = sc_list.GetSize();
1664b36f791SVedant Kumar     if (num_matches == 0 || !sc_list[0].symbol) {
1674fdbc072SVedant Kumar       LLDB_LOG(log,
1684fdbc072SVedant Kumar                "DirectCallEdge: Found no symbols for {0}, cannot resolve it",
1694b36f791SVedant Kumar                callee_name);
1704b36f791SVedant Kumar       return nullptr;
1714b36f791SVedant Kumar     }
1724b36f791SVedant Kumar     Address callee_addr = sc_list[0].symbol->GetAddress();
1734b36f791SVedant Kumar     if (!callee_addr.IsValid()) {
1744fdbc072SVedant Kumar       LLDB_LOG(log, "DirectCallEdge: Invalid symbol address");
1754b36f791SVedant Kumar       return nullptr;
1764b36f791SVedant Kumar     }
1774b36f791SVedant Kumar     Function *f = callee_addr.CalculateSymbolContextFunction();
1784b36f791SVedant Kumar     if (!f) {
1794fdbc072SVedant Kumar       LLDB_LOG(log, "DirectCallEdge: Could not find complete function");
1804b36f791SVedant Kumar       return nullptr;
1814b36f791SVedant Kumar     }
1824b36f791SVedant Kumar     return f;
1834b36f791SVedant Kumar   };
1844b36f791SVedant Kumar   lazy_callee.def = resolve_lazy_callee();
1854b36f791SVedant Kumar   resolved = true;
1864b36f791SVedant Kumar }
1874b36f791SVedant Kumar 
GetCallee(ModuleList & images,ExecutionContext &)1884fdbc072SVedant Kumar Function *DirectCallEdge::GetCallee(ModuleList &images, ExecutionContext &) {
1894b36f791SVedant Kumar   ParseSymbolFileAndResolve(images);
190c03c2e88SVedant Kumar   assert(resolved && "Did not resolve lazy callee");
1914b36f791SVedant Kumar   return lazy_callee.def;
1924b36f791SVedant Kumar }
1934b36f791SVedant Kumar 
GetCallee(ModuleList & images,ExecutionContext & exe_ctx)1944fdbc072SVedant Kumar Function *IndirectCallEdge::GetCallee(ModuleList &images,
1954fdbc072SVedant Kumar                                       ExecutionContext &exe_ctx) {
196a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Step);
1974fdbc072SVedant Kumar   Status error;
1984fdbc072SVedant Kumar   Value callee_addr_val;
199b74a01a8SZequan Wu   if (!call_target.Evaluate(
200b74a01a8SZequan Wu           &exe_ctx, exe_ctx.GetRegisterContext(), LLDB_INVALID_ADDRESS,
2014fdbc072SVedant Kumar           /*initial_value_ptr=*/nullptr,
202b74a01a8SZequan Wu           /*object_address_ptr=*/nullptr, callee_addr_val, &error)) {
2034fdbc072SVedant Kumar     LLDB_LOGF(log, "IndirectCallEdge: Could not evaluate expression: %s",
2044fdbc072SVedant Kumar               error.AsCString());
2054fdbc072SVedant Kumar     return nullptr;
2064b36f791SVedant Kumar   }
2074b36f791SVedant Kumar 
2084fdbc072SVedant Kumar   addr_t raw_addr = callee_addr_val.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2094fdbc072SVedant Kumar   if (raw_addr == LLDB_INVALID_ADDRESS) {
2104fdbc072SVedant Kumar     LLDB_LOG(log, "IndirectCallEdge: Could not extract address from scalar");
2114fdbc072SVedant Kumar     return nullptr;
2124fdbc072SVedant Kumar   }
2134fdbc072SVedant Kumar 
2144fdbc072SVedant Kumar   Address callee_addr;
2154fdbc072SVedant Kumar   if (!exe_ctx.GetTargetPtr()->ResolveLoadAddress(raw_addr, callee_addr)) {
2164fdbc072SVedant Kumar     LLDB_LOG(log, "IndirectCallEdge: Could not resolve callee's load address");
2174fdbc072SVedant Kumar     return nullptr;
2184fdbc072SVedant Kumar   }
2194fdbc072SVedant Kumar 
2204fdbc072SVedant Kumar   Function *f = callee_addr.CalculateSymbolContextFunction();
2214fdbc072SVedant Kumar   if (!f) {
2224fdbc072SVedant Kumar     LLDB_LOG(log, "IndirectCallEdge: Could not find complete function");
2234fdbc072SVedant Kumar     return nullptr;
2244fdbc072SVedant Kumar   }
2254fdbc072SVedant Kumar 
2264fdbc072SVedant Kumar   return f;
2274fdbc072SVedant Kumar }
2284fdbc072SVedant Kumar 
2294fdbc072SVedant Kumar /// @}
2304fdbc072SVedant Kumar 
2314b36f791SVedant Kumar //
Function(CompileUnit * comp_unit,lldb::user_id_t func_uid,lldb::user_id_t type_uid,const Mangled & mangled,Type * type,const AddressRange & range)232b9c1b51eSKate Stone Function::Function(CompileUnit *comp_unit, lldb::user_id_t func_uid,
233b9c1b51eSKate Stone                    lldb::user_id_t type_uid, const Mangled &mangled, Type *type,
234b9c1b51eSKate Stone                    const AddressRange &range)
235b9c1b51eSKate Stone     : UserID(func_uid), m_comp_unit(comp_unit), m_type_uid(type_uid),
236b9c1b51eSKate Stone       m_type(type), m_mangled(mangled), m_block(func_uid), m_range(range),
23704a087acSJonas Devlieghere       m_frame_base(), m_flags(), m_prologue_byte_size(0) {
2380b76a2c2SGreg Clayton   m_block.SetParentScope(this);
239d4612ad0SEd Maste   assert(comp_unit != nullptr);
24030fdc8d8SChris Lattner }
24130fdc8d8SChris Lattner 
242fd2433e1SJonas Devlieghere Function::~Function() = default;
24330fdc8d8SChris Lattner 
GetStartLineSourceInfo(FileSpec & source_file,uint32_t & line_no)244b9c1b51eSKate Stone void Function::GetStartLineSourceInfo(FileSpec &source_file,
245b9c1b51eSKate Stone                                       uint32_t &line_no) {
24699760336SJim Ingham   line_no = 0;
24799760336SJim Ingham   source_file.Clear();
24899760336SJim Ingham 
249d4612ad0SEd Maste   if (m_comp_unit == nullptr)
25099760336SJim Ingham     return;
25199760336SJim Ingham 
252f81f15a7SJason Molenda   // Initialize m_type if it hasn't been initialized already
253f81f15a7SJason Molenda   GetType();
254f81f15a7SJason Molenda 
255b9c1b51eSKate Stone   if (m_type != nullptr && m_type->GetDeclaration().GetLine() != 0) {
25699760336SJim Ingham     source_file = m_type->GetDeclaration().GetFile();
25799760336SJim Ingham     line_no = m_type->GetDeclaration().GetLine();
258b9c1b51eSKate Stone   } else {
25999760336SJim Ingham     LineTable *line_table = m_comp_unit->GetLineTable();
260d4612ad0SEd Maste     if (line_table == nullptr)
26199760336SJim Ingham       return;
26299760336SJim Ingham 
26399760336SJim Ingham     LineEntry line_entry;
264b9c1b51eSKate Stone     if (line_table->FindLineEntryByAddress(GetAddressRange().GetBaseAddress(),
265b9c1b51eSKate Stone                                            line_entry, nullptr)) {
26699760336SJim Ingham       line_no = line_entry.line;
26799760336SJim Ingham       source_file = line_entry.file;
26899760336SJim Ingham     }
26999760336SJim Ingham   }
27099760336SJim Ingham }
27199760336SJim Ingham 
GetEndLineSourceInfo(FileSpec & source_file,uint32_t & line_no)272b9c1b51eSKate Stone void Function::GetEndLineSourceInfo(FileSpec &source_file, uint32_t &line_no) {
27399760336SJim Ingham   line_no = 0;
27499760336SJim Ingham   source_file.Clear();
27599760336SJim Ingham 
276b9c1b51eSKate Stone   // The -1 is kind of cheesy, but I want to get the last line entry for the
27705097246SAdrian Prantl   // given function, not the first entry of the next.
27899760336SJim Ingham   Address scratch_addr(GetAddressRange().GetBaseAddress());
279b9c1b51eSKate Stone   scratch_addr.SetOffset(scratch_addr.GetOffset() +
280b9c1b51eSKate Stone                          GetAddressRange().GetByteSize() - 1);
28199760336SJim Ingham 
28299760336SJim Ingham   LineTable *line_table = m_comp_unit->GetLineTable();
283d4612ad0SEd Maste   if (line_table == nullptr)
28499760336SJim Ingham     return;
28599760336SJim Ingham 
28699760336SJim Ingham   LineEntry line_entry;
287b9c1b51eSKate Stone   if (line_table->FindLineEntryByAddress(scratch_addr, line_entry, nullptr)) {
28899760336SJim Ingham     line_no = line_entry.line;
28999760336SJim Ingham     source_file = line_entry.file;
29099760336SJim Ingham   }
29199760336SJim Ingham }
29299760336SJim Ingham 
GetCallEdges()2934fdbc072SVedant Kumar llvm::ArrayRef<std::unique_ptr<CallEdge>> Function::GetCallEdges() {
2946cfc90b9SVedant Kumar   std::lock_guard<std::mutex> guard(m_call_edges_lock);
2956cfc90b9SVedant Kumar 
2964b36f791SVedant Kumar   if (m_call_edges_resolved)
2974b36f791SVedant Kumar     return m_call_edges;
2984b36f791SVedant Kumar 
299a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Step);
3004b36f791SVedant Kumar   LLDB_LOG(log, "GetCallEdges: Attempting to parse call site info for {0}",
3014b36f791SVedant Kumar            GetDisplayName());
3024b36f791SVedant Kumar 
3034b36f791SVedant Kumar   m_call_edges_resolved = true;
3044b36f791SVedant Kumar 
3054b36f791SVedant Kumar   // Find the SymbolFile which provided this function's definition.
3064b36f791SVedant Kumar   Block &block = GetBlock(/*can_create*/true);
3074b36f791SVedant Kumar   SymbolFile *sym_file = block.GetSymbolFile();
3084b36f791SVedant Kumar   if (!sym_file)
3094b36f791SVedant Kumar     return llvm::None;
3104b36f791SVedant Kumar 
3114b36f791SVedant Kumar   // Lazily read call site information from the SymbolFile.
3124b36f791SVedant Kumar   m_call_edges = sym_file->ParseCallEdgesInFunction(GetID());
3134b36f791SVedant Kumar 
3144b36f791SVedant Kumar   // Sort the call edges to speed up return_pc lookups.
3150081149fSPavel Labath   llvm::sort(m_call_edges, [](const std::unique_ptr<CallEdge> &LHS,
3164fdbc072SVedant Kumar                               const std::unique_ptr<CallEdge> &RHS) {
3170081149fSPavel Labath     return LHS->GetSortKey() < RHS->GetSortKey();
3184b36f791SVedant Kumar   });
3194b36f791SVedant Kumar 
3204b36f791SVedant Kumar   return m_call_edges;
3214b36f791SVedant Kumar }
3224b36f791SVedant Kumar 
GetTailCallingEdges()3234fdbc072SVedant Kumar llvm::ArrayRef<std::unique_ptr<CallEdge>> Function::GetTailCallingEdges() {
3240081149fSPavel Labath   // Tail calling edges are sorted at the end of the list. Find them by dropping
3250081149fSPavel Labath   // all non-tail-calls.
3260081149fSPavel Labath   return GetCallEdges().drop_until(
3270081149fSPavel Labath       [](const std::unique_ptr<CallEdge> &edge) { return edge->IsTailCall(); });
3284b36f791SVedant Kumar }
3294b36f791SVedant Kumar 
GetCallEdgeForReturnAddress(addr_t return_pc,Target & target)330ff02109aSVedant Kumar CallEdge *Function::GetCallEdgeForReturnAddress(addr_t return_pc,
331ff02109aSVedant Kumar                                                 Target &target) {
332ff02109aSVedant Kumar   auto edges = GetCallEdges();
333ff02109aSVedant Kumar   auto edge_it =
3340081149fSPavel Labath       llvm::partition_point(edges, [&](const std::unique_ptr<CallEdge> &edge) {
3350081149fSPavel Labath         return std::make_pair(edge->IsTailCall(),
3360081149fSPavel Labath                               edge->GetReturnPCAddress(*this, target)) <
3370081149fSPavel Labath                std::make_pair(false, return_pc);
338ff02109aSVedant Kumar       });
339ff02109aSVedant Kumar   if (edge_it == edges.end() ||
3404fdbc072SVedant Kumar       edge_it->get()->GetReturnPCAddress(*this, target) != return_pc)
341ff02109aSVedant Kumar     return nullptr;
3420081149fSPavel Labath   return edge_it->get();
343ff02109aSVedant Kumar }
344ff02109aSVedant Kumar 
GetBlock(bool can_create)345b9c1b51eSKate Stone Block &Function::GetBlock(bool can_create) {
346b9c1b51eSKate Stone   if (!m_block.BlockInfoHasBeenParsed() && can_create) {
347ffc1b8fdSZachary Turner     ModuleSP module_sp = CalculateSymbolContextModule();
348ffc1b8fdSZachary Turner     if (module_sp) {
349465eae36SPavel Labath       module_sp->GetSymbolFile()->ParseBlocksRecursive(*this);
350b9c1b51eSKate Stone     } else {
35168793919SJonas Devlieghere       Debugger::ReportError(llvm::formatv(
35268793919SJonas Devlieghere           "unable to find module shared pointer for function '{0}' in {1}",
35368793919SJonas Devlieghere           GetName().GetCString(), m_comp_unit->GetPrimaryFile().GetPath()));
35417cc8b9dSGreg Clayton     }
3550b76a2c2SGreg Clayton     m_block.SetBlockInfoHasBeenParsed(true, true);
35630fdc8d8SChris Lattner   }
3570b76a2c2SGreg Clayton   return m_block;
35830fdc8d8SChris Lattner }
35930fdc8d8SChris Lattner 
GetCompileUnit()360b9c1b51eSKate Stone CompileUnit *Function::GetCompileUnit() { return m_comp_unit; }
36130fdc8d8SChris Lattner 
GetCompileUnit() const362b9c1b51eSKate Stone const CompileUnit *Function::GetCompileUnit() const { return m_comp_unit; }
36330fdc8d8SChris Lattner 
GetDescription(Stream * s,lldb::DescriptionLevel level,Target * target)364b9c1b51eSKate Stone void Function::GetDescription(Stream *s, lldb::DescriptionLevel level,
365b9c1b51eSKate Stone                               Target *target) {
366b663010fSGreg Clayton   ConstString name = GetName();
367b663010fSGreg Clayton   ConstString mangled = m_mangled.GetMangledName();
36828eb5711SJim Ingham 
369b663010fSGreg Clayton   *s << "id = " << (const UserID &)*this;
370b663010fSGreg Clayton   if (name)
371bca378f6SRaphael Isemann     s->AsRawOstream() << ", name = \"" << name << '"';
372b663010fSGreg Clayton   if (mangled)
373bca378f6SRaphael Isemann     s->AsRawOstream() << ", mangled = \"" << mangled << '"';
374b663010fSGreg Clayton   *s << ", range = ";
375c9800667SGreg Clayton   Address::DumpStyle fallback_style;
376c9800667SGreg Clayton   if (level == eDescriptionLevelVerbose)
377c9800667SGreg Clayton     fallback_style = Address::DumpStyleModuleWithFileAddress;
378c9800667SGreg Clayton   else
379c9800667SGreg Clayton     fallback_style = Address::DumpStyleFileAddress;
380b9c1b51eSKate Stone   GetAddressRange().Dump(s, target, Address::DumpStyleLoadAddress,
381b9c1b51eSKate Stone                          fallback_style);
3820c5cd90dSGreg Clayton }
3830c5cd90dSGreg Clayton 
Dump(Stream * s,bool show_context) const384b9c1b51eSKate Stone void Function::Dump(Stream *s, bool show_context) const {
385324a1036SSaleem Abdulrasool   s->Printf("%p: ", static_cast<const void *>(this));
38630fdc8d8SChris Lattner   s->Indent();
387324a1036SSaleem Abdulrasool   *s << "Function" << static_cast<const UserID &>(*this);
38830fdc8d8SChris Lattner 
38930fdc8d8SChris Lattner   m_mangled.Dump(s);
39030fdc8d8SChris Lattner 
39130fdc8d8SChris Lattner   if (m_type)
392324a1036SSaleem Abdulrasool     s->Printf(", type = %p", static_cast<void *>(m_type));
39330fdc8d8SChris Lattner   else if (m_type_uid != LLDB_INVALID_UID)
394d01b2953SDaniel Malea     s->Printf(", type_uid = 0x%8.8" PRIx64, m_type_uid);
39530fdc8d8SChris Lattner 
39630fdc8d8SChris Lattner   s->EOL();
39730fdc8d8SChris Lattner   // Dump the root object
3980b76a2c2SGreg Clayton   if (m_block.BlockInfoHasBeenParsed())
399b9c1b51eSKate Stone     m_block.Dump(s, m_range.GetBaseAddress().GetFileAddress(), INT_MAX,
400b9c1b51eSKate Stone                  show_context);
40130fdc8d8SChris Lattner }
40230fdc8d8SChris Lattner 
CalculateSymbolContext(SymbolContext * sc)403b9c1b51eSKate Stone void Function::CalculateSymbolContext(SymbolContext *sc) {
40430fdc8d8SChris Lattner   sc->function = this;
40530fdc8d8SChris Lattner   m_comp_unit->CalculateSymbolContext(sc);
40630fdc8d8SChris Lattner }
40730fdc8d8SChris Lattner 
CalculateSymbolContextModule()408b9c1b51eSKate Stone ModuleSP Function::CalculateSymbolContextModule() {
409e72dfb32SGreg Clayton   SectionSP section_sp(m_range.GetBaseAddress().GetSection());
410e72dfb32SGreg Clayton   if (section_sp)
411e72dfb32SGreg Clayton     return section_sp->GetModule();
412881ec853SJim Ingham 
4137e9b1fd0SGreg Clayton   return this->GetCompileUnit()->GetModule();
4147e9b1fd0SGreg Clayton }
4157e9b1fd0SGreg Clayton 
CalculateSymbolContextCompileUnit()416b9c1b51eSKate Stone CompileUnit *Function::CalculateSymbolContextCompileUnit() {
4177e9b1fd0SGreg Clayton   return this->GetCompileUnit();
4187e9b1fd0SGreg Clayton }
4197e9b1fd0SGreg Clayton 
CalculateSymbolContextFunction()420b9c1b51eSKate Stone Function *Function::CalculateSymbolContextFunction() { return this; }
4217e9b1fd0SGreg Clayton 
GetInstructions(const ExecutionContext & exe_ctx,const char * flavor,bool prefer_file_cache)422b9c1b51eSKate Stone lldb::DisassemblerSP Function::GetInstructions(const ExecutionContext &exe_ctx,
42344d93782SGreg Clayton                                                const char *flavor,
424b9c1b51eSKate Stone                                                bool prefer_file_cache) {
42544d93782SGreg Clayton   ModuleSP module_sp(GetAddressRange().GetBaseAddress().GetModule());
42604592d5bSPavel Labath   if (module_sp && exe_ctx.HasTargetScope()) {
427b9c1b51eSKate Stone     return Disassembler::DisassembleRange(module_sp->GetArchitecture(), nullptr,
42804592d5bSPavel Labath                                           flavor, exe_ctx.GetTargetRef(),
429e9fe788dSJason Molenda                                           GetAddressRange(), !prefer_file_cache);
43044d93782SGreg Clayton   }
43144d93782SGreg Clayton   return lldb::DisassemblerSP();
43244d93782SGreg Clayton }
43344d93782SGreg Clayton 
GetDisassembly(const ExecutionContext & exe_ctx,const char * flavor,Stream & strm,bool prefer_file_cache)434b9c1b51eSKate Stone bool Function::GetDisassembly(const ExecutionContext &exe_ctx,
435e9fe788dSJason Molenda                               const char *flavor, Stream &strm,
436e9fe788dSJason Molenda                               bool prefer_file_cache) {
437b9c1b51eSKate Stone   lldb::DisassemblerSP disassembler_sp =
438b9c1b51eSKate Stone       GetInstructions(exe_ctx, flavor, prefer_file_cache);
439b9c1b51eSKate Stone   if (disassembler_sp) {
44044d93782SGreg Clayton     const bool show_address = true;
44144d93782SGreg Clayton     const bool show_bytes = false;
442*ad7bcda9SWalter Erquinigo     const bool show_control_flow_kind = false;
443*ad7bcda9SWalter Erquinigo     disassembler_sp->GetInstructionList().Dump(
444*ad7bcda9SWalter Erquinigo         &strm, show_address, show_bytes, show_control_flow_kind, &exe_ctx);
44544d93782SGreg Clayton     return true;
44644d93782SGreg Clayton   }
44744d93782SGreg Clayton   return false;
44844d93782SGreg Clayton }
44944d93782SGreg Clayton 
4507e9b1fd0SGreg Clayton // Symbol *
4517e9b1fd0SGreg Clayton // Function::CalculateSymbolContextSymbol ()
4527e9b1fd0SGreg Clayton //{
4537e9b1fd0SGreg Clayton //    return // TODO: find the symbol for the function???
4547e9b1fd0SGreg Clayton //}
4557e9b1fd0SGreg Clayton 
DumpSymbolContext(Stream * s)456b9c1b51eSKate Stone void Function::DumpSymbolContext(Stream *s) {
45730fdc8d8SChris Lattner   m_comp_unit->DumpSymbolContext(s);
458d01b2953SDaniel Malea   s->Printf(", Function{0x%8.8" PRIx64 "}", GetID());
45930fdc8d8SChris Lattner }
46030fdc8d8SChris Lattner 
MemorySize() const461b9c1b51eSKate Stone size_t Function::MemorySize() const {
4620b76a2c2SGreg Clayton   size_t mem_size = sizeof(Function) + m_block.MemorySize();
46330fdc8d8SChris Lattner   return mem_size;
46430fdc8d8SChris Lattner }
46530fdc8d8SChris Lattner 
GetIsOptimized()466b9c1b51eSKate Stone bool Function::GetIsOptimized() {
4676ab659a9SJason Molenda   bool result = false;
4686ab659a9SJason Molenda 
46905097246SAdrian Prantl   // Currently optimization is only indicted by the vendor extension
47005097246SAdrian Prantl   // DW_AT_APPLE_optimized which is set on a compile unit level.
471b9c1b51eSKate Stone   if (m_comp_unit) {
4726ab659a9SJason Molenda     result = m_comp_unit->GetIsOptimized();
4736ab659a9SJason Molenda   }
4746ab659a9SJason Molenda   return result;
4756ab659a9SJason Molenda }
4766ab659a9SJason Molenda 
IsTopLevelFunction()477b9c1b51eSKate Stone bool Function::IsTopLevelFunction() {
4786754e04fSEnrico Granata   bool result = false;
4796754e04fSEnrico Granata 
4806754e04fSEnrico Granata   if (Language *language = Language::FindPlugin(GetLanguage()))
4816754e04fSEnrico Granata     result = language->IsTopLevelFunction(*this);
4826754e04fSEnrico Granata 
4836754e04fSEnrico Granata   return result;
4846754e04fSEnrico Granata }
4856754e04fSEnrico Granata 
GetDisplayName() const486b9c1b51eSKate Stone ConstString Function::GetDisplayName() const {
48722b04487SAlex Langford   return m_mangled.GetDisplayDemangledName();
488c1f705c2SEnrico Granata }
489c1f705c2SEnrico Granata 
GetDeclContext()490b9c1b51eSKate Stone CompilerDeclContext Function::GetDeclContext() {
49199558cc4SGreg Clayton   ModuleSP module_sp = CalculateSymbolContextModule();
49272e4940bSSean Callanan 
493b9c1b51eSKate Stone   if (module_sp) {
49423f70e83SPavel Labath     if (SymbolFile *sym_file = module_sp->GetSymbolFile())
49599558cc4SGreg Clayton       return sym_file->GetDeclContextForUID(GetID());
49699558cc4SGreg Clayton   }
49799558cc4SGreg Clayton   return CompilerDeclContext();
49872e4940bSSean Callanan }
49972e4940bSSean Callanan 
GetType()500b9c1b51eSKate Stone Type *Function::GetType() {
501b9c1b51eSKate Stone   if (m_type == nullptr) {
5022bc22f83SGreg Clayton     SymbolContext sc;
5032bc22f83SGreg Clayton 
5042bc22f83SGreg Clayton     CalculateSymbolContext(&sc);
5052bc22f83SGreg Clayton 
5062bc22f83SGreg Clayton     if (!sc.module_sp)
507d4612ad0SEd Maste       return nullptr;
5082bc22f83SGreg Clayton 
50923f70e83SPavel Labath     SymbolFile *sym_file = sc.module_sp->GetSymbolFile();
5102bc22f83SGreg Clayton 
511d4612ad0SEd Maste     if (sym_file == nullptr)
512d4612ad0SEd Maste       return nullptr;
5132bc22f83SGreg Clayton 
5145cf58b9bSGreg Clayton     m_type = sym_file->ResolveTypeUID(m_type_uid);
5152bc22f83SGreg Clayton   }
51630fdc8d8SChris Lattner   return m_type;
51730fdc8d8SChris Lattner }
51830fdc8d8SChris Lattner 
GetType() const519b9c1b51eSKate Stone const Type *Function::GetType() const { return m_type; }
52030fdc8d8SChris Lattner 
GetCompilerType()521b9c1b51eSKate Stone CompilerType Function::GetCompilerType() {
52257ee3067SGreg Clayton   Type *function_type = GetType();
523f4ecaa57SGreg Clayton   if (function_type)
52499558cc4SGreg Clayton     return function_type->GetFullCompilerType();
525a1e5dc86SGreg Clayton   return CompilerType();
52630fdc8d8SChris Lattner }
52730fdc8d8SChris Lattner 
GetPrologueByteSize()528b9c1b51eSKate Stone uint32_t Function::GetPrologueByteSize() {
529b9c1b51eSKate Stone   if (m_prologue_byte_size == 0 &&
530b9c1b51eSKate Stone       m_flags.IsClear(flagsCalculatedPrologueSize)) {
53130fdc8d8SChris Lattner     m_flags.Set(flagsCalculatedPrologueSize);
53230fdc8d8SChris Lattner     LineTable *line_table = m_comp_unit->GetLineTable();
53339f7353aSJim Ingham     uint32_t prologue_end_line_idx = 0;
53439f7353aSJim Ingham 
535b9c1b51eSKate Stone     if (line_table) {
53683b6fabdSGreg Clayton       LineEntry first_line_entry;
53783b6fabdSGreg Clayton       uint32_t first_line_entry_idx = UINT32_MAX;
538b9c1b51eSKate Stone       if (line_table->FindLineEntryByAddress(GetAddressRange().GetBaseAddress(),
539b9c1b51eSKate Stone                                              first_line_entry,
540b9c1b51eSKate Stone                                              &first_line_entry_idx)) {
54183b6fabdSGreg Clayton         // Make sure the first line entry isn't already the end of the prologue
54283b6fabdSGreg Clayton         addr_t prologue_end_file_addr = LLDB_INVALID_ADDRESS;
54339f7353aSJim Ingham         addr_t line_zero_end_file_addr = LLDB_INVALID_ADDRESS;
54439f7353aSJim Ingham 
545b9c1b51eSKate Stone         if (first_line_entry.is_prologue_end) {
546b9c1b51eSKate Stone           prologue_end_file_addr =
547b9c1b51eSKate Stone               first_line_entry.range.GetBaseAddress().GetFileAddress();
54839f7353aSJim Ingham           prologue_end_line_idx = first_line_entry_idx;
549b9c1b51eSKate Stone         } else {
55083b6fabdSGreg Clayton           // Check the first few instructions and look for one that has
55183b6fabdSGreg Clayton           // is_prologue_end set to true.
55283b6fabdSGreg Clayton           const uint32_t last_line_entry_idx = first_line_entry_idx + 6;
553b9c1b51eSKate Stone           for (uint32_t idx = first_line_entry_idx + 1;
554b9c1b51eSKate Stone                idx < last_line_entry_idx; ++idx) {
555a7499c98SMichael Sartain             LineEntry line_entry;
556b9c1b51eSKate Stone             if (line_table->GetLineEntryAtIndex(idx, line_entry)) {
557b9c1b51eSKate Stone               if (line_entry.is_prologue_end) {
558b9c1b51eSKate Stone                 prologue_end_file_addr =
559b9c1b51eSKate Stone                     line_entry.range.GetBaseAddress().GetFileAddress();
56039f7353aSJim Ingham                 prologue_end_line_idx = idx;
56183b6fabdSGreg Clayton                 break;
56283b6fabdSGreg Clayton               }
56383b6fabdSGreg Clayton             }
56483b6fabdSGreg Clayton           }
56583b6fabdSGreg Clayton         }
56683b6fabdSGreg Clayton 
56705097246SAdrian Prantl         // If we didn't find the end of the prologue in the line tables, then
56805097246SAdrian Prantl         // just use the end address of the first line table entry
569b9c1b51eSKate Stone         if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) {
57005097246SAdrian Prantl           // Check the first few instructions and look for one that has a line
57105097246SAdrian Prantl           // number that's different than the first entry.
57239f7353aSJim Ingham           uint32_t last_line_entry_idx = first_line_entry_idx + 6;
573b9c1b51eSKate Stone           for (uint32_t idx = first_line_entry_idx + 1;
574b9c1b51eSKate Stone                idx < last_line_entry_idx; ++idx) {
575a7499c98SMichael Sartain             LineEntry line_entry;
576b9c1b51eSKate Stone             if (line_table->GetLineEntryAtIndex(idx, line_entry)) {
577b9c1b51eSKate Stone               if (line_entry.line != first_line_entry.line) {
578b9c1b51eSKate Stone                 prologue_end_file_addr =
579b9c1b51eSKate Stone                     line_entry.range.GetBaseAddress().GetFileAddress();
58039f7353aSJim Ingham                 prologue_end_line_idx = idx;
581a7499c98SMichael Sartain                 break;
582a7499c98SMichael Sartain               }
583a7499c98SMichael Sartain             }
584a7499c98SMichael Sartain           }
585a7499c98SMichael Sartain 
586b9c1b51eSKate Stone           if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) {
587b9c1b51eSKate Stone             prologue_end_file_addr =
588b9c1b51eSKate Stone                 first_line_entry.range.GetBaseAddress().GetFileAddress() +
589b9c1b51eSKate Stone                 first_line_entry.range.GetByteSize();
59039f7353aSJim Ingham             prologue_end_line_idx = first_line_entry_idx;
59183b6fabdSGreg Clayton           }
592a7499c98SMichael Sartain         }
59339f7353aSJim Ingham 
594b9c1b51eSKate Stone         const addr_t func_start_file_addr =
595b9c1b51eSKate Stone             m_range.GetBaseAddress().GetFileAddress();
596b9c1b51eSKate Stone         const addr_t func_end_file_addr =
597b9c1b51eSKate Stone             func_start_file_addr + m_range.GetByteSize();
59883b6fabdSGreg Clayton 
59939f7353aSJim Ingham         // Now calculate the offset to pass the subsequent line 0 entries.
60039f7353aSJim Ingham         uint32_t first_non_zero_line = prologue_end_line_idx;
60109ad8c8fSJonas Devlieghere         while (true) {
60239f7353aSJim Ingham           LineEntry line_entry;
603b9c1b51eSKate Stone           if (line_table->GetLineEntryAtIndex(first_non_zero_line,
604b9c1b51eSKate Stone                                               line_entry)) {
60539f7353aSJim Ingham             if (line_entry.line != 0)
60639f7353aSJim Ingham               break;
60739f7353aSJim Ingham           }
608b9c1b51eSKate Stone           if (line_entry.range.GetBaseAddress().GetFileAddress() >=
609b9c1b51eSKate Stone               func_end_file_addr)
61039f7353aSJim Ingham             break;
61139f7353aSJim Ingham 
61239f7353aSJim Ingham           first_non_zero_line++;
61339f7353aSJim Ingham         }
61439f7353aSJim Ingham 
615b9c1b51eSKate Stone         if (first_non_zero_line > prologue_end_line_idx) {
61639f7353aSJim Ingham           LineEntry first_non_zero_entry;
617b9c1b51eSKate Stone           if (line_table->GetLineEntryAtIndex(first_non_zero_line,
618b9c1b51eSKate Stone                                               first_non_zero_entry)) {
619b9c1b51eSKate Stone             line_zero_end_file_addr =
620b9c1b51eSKate Stone                 first_non_zero_entry.range.GetBaseAddress().GetFileAddress();
62139f7353aSJim Ingham           }
62239f7353aSJim Ingham         }
62339f7353aSJim Ingham 
62405097246SAdrian Prantl         // Verify that this prologue end file address in the function's address
62505097246SAdrian Prantl         // range just to be sure
626b9c1b51eSKate Stone         if (func_start_file_addr < prologue_end_file_addr &&
627b9c1b51eSKate Stone             prologue_end_file_addr < func_end_file_addr) {
62883b6fabdSGreg Clayton           m_prologue_byte_size = prologue_end_file_addr - func_start_file_addr;
62983b6fabdSGreg Clayton         }
63039f7353aSJim Ingham 
631b9c1b51eSKate Stone         if (prologue_end_file_addr < line_zero_end_file_addr &&
632b9c1b51eSKate Stone             line_zero_end_file_addr < func_end_file_addr) {
633b9c1b51eSKate Stone           m_prologue_byte_size +=
634b9c1b51eSKate Stone               line_zero_end_file_addr - prologue_end_file_addr;
635c3b84997SGreg Clayton         }
63630fdc8d8SChris Lattner       }
63730fdc8d8SChris Lattner     }
63839f7353aSJim Ingham   }
63939f7353aSJim Ingham 
64030fdc8d8SChris Lattner   return m_prologue_byte_size;
64130fdc8d8SChris Lattner }
64230fdc8d8SChris Lattner 
GetLanguage() const643b9c1b51eSKate Stone lldb::LanguageType Function::GetLanguage() const {
644d7fcee62SAlex Langford   lldb::LanguageType lang = m_mangled.GuessLanguage();
645d7fcee62SAlex Langford   if (lang != lldb::eLanguageTypeUnknown)
646d7fcee62SAlex Langford     return lang;
647d7fcee62SAlex Langford 
648ddaf6a72SGreg Clayton   if (m_comp_unit)
649ddaf6a72SGreg Clayton     return m_comp_unit->GetLanguage();
650d7fcee62SAlex Langford 
651ddaf6a72SGreg Clayton   return lldb::eLanguageTypeUnknown;
652ddaf6a72SGreg Clayton }
653ddaf6a72SGreg Clayton 
GetName() const654b9c1b51eSKate Stone ConstString Function::GetName() const {
65522b04487SAlex Langford   return m_mangled.GetName();
656ddaf6a72SGreg Clayton }
657ddaf6a72SGreg Clayton 
GetNameNoArguments() const658b9c1b51eSKate Stone ConstString Function::GetNameNoArguments() const {
65922b04487SAlex Langford   return m_mangled.GetName(Mangled::ePreferDemangledWithoutArguments);
660ddaf6a72SGreg Clayton }
661