1 //===-- Function.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Symbol/Function.h"
11 #include "lldb/Core/Disassembler.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ModuleList.h"
14 #include "lldb/Core/Section.h"
15 #include "lldb/Host/Host.h"
16 #include "lldb/Symbol/CompileUnit.h"
17 #include "lldb/Symbol/CompilerType.h"
18 #include "lldb/Symbol/LineTable.h"
19 #include "lldb/Symbol/SymbolFile.h"
20 #include "lldb/Symbol/SymbolVendor.h"
21 #include "lldb/Target/Language.h"
22 #include "lldb/Utility/Log.h"
23 #include "llvm/Support/Casting.h"
26 using namespace lldb_private;
28 //----------------------------------------------------------------------
29 // Basic function information is contained in the FunctionInfo class. It is
30 // designed to contain the name, linkage name, and declaration location.
31 //----------------------------------------------------------------------
32 FunctionInfo::FunctionInfo(const char *name, const Declaration *decl_ptr)
33 : m_name(name), m_declaration(decl_ptr) {}
35 FunctionInfo::FunctionInfo(const ConstString &name, const Declaration *decl_ptr)
36 : m_name(name), m_declaration(decl_ptr) {}
38 FunctionInfo::~FunctionInfo() {}
40 void FunctionInfo::Dump(Stream *s, bool show_fullpaths) const {
42 *s << ", name = \"" << m_name << "\"";
43 m_declaration.Dump(s, show_fullpaths);
46 int FunctionInfo::Compare(const FunctionInfo &a, const FunctionInfo &b) {
47 int result = ConstString::Compare(a.GetName(), b.GetName());
51 return Declaration::Compare(a.m_declaration, b.m_declaration);
54 Declaration &FunctionInfo::GetDeclaration() { return m_declaration; }
56 const Declaration &FunctionInfo::GetDeclaration() const {
60 ConstString FunctionInfo::GetName() const { return m_name; }
62 size_t FunctionInfo::MemorySize() const {
63 return m_name.MemorySize() + m_declaration.MemorySize();
66 InlineFunctionInfo::InlineFunctionInfo(const char *name, const char *mangled,
67 const Declaration *decl_ptr,
68 const Declaration *call_decl_ptr)
69 : FunctionInfo(name, decl_ptr), m_mangled(ConstString(mangled), true),
70 m_call_decl(call_decl_ptr) {}
72 InlineFunctionInfo::InlineFunctionInfo(const ConstString &name,
73 const Mangled &mangled,
74 const Declaration *decl_ptr,
75 const Declaration *call_decl_ptr)
76 : FunctionInfo(name, decl_ptr), m_mangled(mangled),
77 m_call_decl(call_decl_ptr) {}
79 InlineFunctionInfo::~InlineFunctionInfo() {}
81 int InlineFunctionInfo::Compare(const InlineFunctionInfo &a,
82 const InlineFunctionInfo &b) {
84 int result = FunctionInfo::Compare(a, b);
87 // only compare the mangled names if both have them
88 return Mangled::Compare(a.m_mangled, a.m_mangled);
91 void InlineFunctionInfo::Dump(Stream *s, bool show_fullpaths) const {
92 FunctionInfo::Dump(s, show_fullpaths);
97 void InlineFunctionInfo::DumpStopContext(Stream *s,
98 LanguageType language) const {
99 // s->Indent("[inlined] ");
102 s->PutCString(m_mangled.GetName(language).AsCString());
104 s->PutCString(m_name.AsCString());
107 ConstString InlineFunctionInfo::GetName(LanguageType language) const {
109 return m_mangled.GetName(language);
113 ConstString InlineFunctionInfo::GetDisplayName(LanguageType language) const {
115 return m_mangled.GetDisplayDemangledName(language);
119 Declaration &InlineFunctionInfo::GetCallSite() { return m_call_decl; }
121 const Declaration &InlineFunctionInfo::GetCallSite() const {
125 Mangled &InlineFunctionInfo::GetMangled() { return m_mangled; }
127 const Mangled &InlineFunctionInfo::GetMangled() const { return m_mangled; }
129 size_t InlineFunctionInfo::MemorySize() const {
130 return FunctionInfo::MemorySize() + m_mangled.MemorySize();
133 //----------------------------------------------------------------------
135 //----------------------------------------------------------------------
136 CallEdge::CallEdge(const char *symbol_name, lldb::addr_t return_pc)
137 : return_pc(return_pc), resolved(false) {
138 lazy_callee.symbol_name = symbol_name;
141 void CallEdge::ParseSymbolFileAndResolve(ModuleList &images) {
145 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
146 LLDB_LOG(log, "CallEdge: Lazily parsing the call graph for {0}",
147 lazy_callee.symbol_name);
149 auto resolve_lazy_callee = [&]() -> Function * {
150 ConstString callee_name{lazy_callee.symbol_name};
151 SymbolContextList sc_list;
153 images.FindFunctionSymbols(callee_name, eFunctionNameTypeAuto, sc_list);
154 if (num_matches == 0 || !sc_list[0].symbol) {
155 LLDB_LOG(log, "CallEdge: Found no symbols for {0}, cannot resolve it",
159 Address callee_addr = sc_list[0].symbol->GetAddress();
160 if (!callee_addr.IsValid()) {
161 LLDB_LOG(log, "CallEdge: Invalid symbol address");
164 Function *f = callee_addr.CalculateSymbolContextFunction();
166 LLDB_LOG(log, "CallEdge: Could not find complete function");
171 lazy_callee.def = resolve_lazy_callee();
175 Function *CallEdge::GetCallee(ModuleList &images) {
176 ParseSymbolFileAndResolve(images);
177 return lazy_callee.def;
180 lldb::addr_t CallEdge::GetReturnPCAddress(Function &caller,
181 Target &target) const {
182 const Address &base = caller.GetAddressRange().GetBaseAddress();
183 return base.GetLoadAddress(&target) + return_pc;
186 //----------------------------------------------------------------------
188 //----------------------------------------------------------------------
189 Function::Function(CompileUnit *comp_unit, lldb::user_id_t func_uid,
190 lldb::user_id_t type_uid, const Mangled &mangled, Type *type,
191 const AddressRange &range)
192 : UserID(func_uid), m_comp_unit(comp_unit), m_type_uid(type_uid),
193 m_type(type), m_mangled(mangled), m_block(func_uid), m_range(range),
194 m_frame_base(nullptr), m_flags(), m_prologue_byte_size(0) {
195 m_block.SetParentScope(this);
196 assert(comp_unit != nullptr);
199 Function::~Function() {}
201 void Function::GetStartLineSourceInfo(FileSpec &source_file,
206 if (m_comp_unit == nullptr)
209 // Initialize m_type if it hasn't been initialized already
212 if (m_type != nullptr && m_type->GetDeclaration().GetLine() != 0) {
213 source_file = m_type->GetDeclaration().GetFile();
214 line_no = m_type->GetDeclaration().GetLine();
216 LineTable *line_table = m_comp_unit->GetLineTable();
217 if (line_table == nullptr)
220 LineEntry line_entry;
221 if (line_table->FindLineEntryByAddress(GetAddressRange().GetBaseAddress(),
222 line_entry, nullptr)) {
223 line_no = line_entry.line;
224 source_file = line_entry.file;
229 void Function::GetEndLineSourceInfo(FileSpec &source_file, uint32_t &line_no) {
233 // The -1 is kind of cheesy, but I want to get the last line entry for the
234 // given function, not the first entry of the next.
235 Address scratch_addr(GetAddressRange().GetBaseAddress());
236 scratch_addr.SetOffset(scratch_addr.GetOffset() +
237 GetAddressRange().GetByteSize() - 1);
239 LineTable *line_table = m_comp_unit->GetLineTable();
240 if (line_table == nullptr)
243 LineEntry line_entry;
244 if (line_table->FindLineEntryByAddress(scratch_addr, line_entry, nullptr)) {
245 line_no = line_entry.line;
246 source_file = line_entry.file;
250 llvm::MutableArrayRef<CallEdge> Function::GetCallEdges() {
251 if (m_call_edges_resolved)
254 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
255 LLDB_LOG(log, "GetCallEdges: Attempting to parse call site info for {0}",
258 m_call_edges_resolved = true;
260 // Find the SymbolFile which provided this function's definition.
261 Block &block = GetBlock(/*can_create*/true);
262 SymbolFile *sym_file = block.GetSymbolFile();
266 // Lazily read call site information from the SymbolFile.
267 m_call_edges = sym_file->ParseCallEdgesInFunction(GetID());
269 // Sort the call edges to speed up return_pc lookups.
270 llvm::sort(m_call_edges.begin(), m_call_edges.end(),
271 [](const CallEdge &LHS, const CallEdge &RHS) {
272 return LHS.GetUnresolvedReturnPCAddress() <
273 RHS.GetUnresolvedReturnPCAddress();
279 llvm::MutableArrayRef<CallEdge> Function::GetTailCallingEdges() {
280 // Call edges are sorted by return PC, and tail calling edges have invalid
281 // return PCs. Find them at the end of the list.
282 return GetCallEdges().drop_until([](const CallEdge &edge) {
283 return edge.GetUnresolvedReturnPCAddress() == LLDB_INVALID_ADDRESS;
287 Block &Function::GetBlock(bool can_create) {
288 if (!m_block.BlockInfoHasBeenParsed() && can_create) {
289 ModuleSP module_sp = CalculateSymbolContextModule();
291 module_sp->GetSymbolVendor()->ParseBlocksRecursive(*this);
293 Host::SystemLog(Host::eSystemLogError,
294 "error: unable to find module "
295 "shared pointer for function '%s' "
297 GetName().GetCString(), m_comp_unit->GetPath().c_str());
299 m_block.SetBlockInfoHasBeenParsed(true, true);
304 CompileUnit *Function::GetCompileUnit() { return m_comp_unit; }
306 const CompileUnit *Function::GetCompileUnit() const { return m_comp_unit; }
308 void Function::GetDescription(Stream *s, lldb::DescriptionLevel level,
310 ConstString name = GetName();
311 ConstString mangled = m_mangled.GetMangledName();
313 *s << "id = " << (const UserID &)*this;
315 *s << ", name = \"" << name.GetCString() << '"';
317 *s << ", mangled = \"" << mangled.GetCString() << '"';
319 Address::DumpStyle fallback_style;
320 if (level == eDescriptionLevelVerbose)
321 fallback_style = Address::DumpStyleModuleWithFileAddress;
323 fallback_style = Address::DumpStyleFileAddress;
324 GetAddressRange().Dump(s, target, Address::DumpStyleLoadAddress,
328 void Function::Dump(Stream *s, bool show_context) const {
329 s->Printf("%p: ", static_cast<const void *>(this));
331 *s << "Function" << static_cast<const UserID &>(*this);
336 s->Printf(", type = %p", static_cast<void *>(m_type));
337 else if (m_type_uid != LLDB_INVALID_UID)
338 s->Printf(", type_uid = 0x%8.8" PRIx64, m_type_uid);
341 // Dump the root object
342 if (m_block.BlockInfoHasBeenParsed())
343 m_block.Dump(s, m_range.GetBaseAddress().GetFileAddress(), INT_MAX,
347 void Function::CalculateSymbolContext(SymbolContext *sc) {
349 m_comp_unit->CalculateSymbolContext(sc);
352 ModuleSP Function::CalculateSymbolContextModule() {
353 SectionSP section_sp(m_range.GetBaseAddress().GetSection());
355 return section_sp->GetModule();
357 return this->GetCompileUnit()->GetModule();
360 CompileUnit *Function::CalculateSymbolContextCompileUnit() {
361 return this->GetCompileUnit();
364 Function *Function::CalculateSymbolContextFunction() { return this; }
366 lldb::DisassemblerSP Function::GetInstructions(const ExecutionContext &exe_ctx,
368 bool prefer_file_cache) {
369 ModuleSP module_sp(GetAddressRange().GetBaseAddress().GetModule());
371 const bool prefer_file_cache = false;
372 return Disassembler::DisassembleRange(module_sp->GetArchitecture(), nullptr,
373 flavor, exe_ctx, GetAddressRange(),
376 return lldb::DisassemblerSP();
379 bool Function::GetDisassembly(const ExecutionContext &exe_ctx,
380 const char *flavor, bool prefer_file_cache,
382 lldb::DisassemblerSP disassembler_sp =
383 GetInstructions(exe_ctx, flavor, prefer_file_cache);
384 if (disassembler_sp) {
385 const bool show_address = true;
386 const bool show_bytes = false;
387 disassembler_sp->GetInstructionList().Dump(&strm, show_address, show_bytes,
395 // Function::CalculateSymbolContextSymbol ()
397 // return // TODO: find the symbol for the function???
400 void Function::DumpSymbolContext(Stream *s) {
401 m_comp_unit->DumpSymbolContext(s);
402 s->Printf(", Function{0x%8.8" PRIx64 "}", GetID());
405 size_t Function::MemorySize() const {
406 size_t mem_size = sizeof(Function) + m_block.MemorySize();
410 bool Function::GetIsOptimized() {
413 // Currently optimization is only indicted by the vendor extension
414 // DW_AT_APPLE_optimized which is set on a compile unit level.
416 result = m_comp_unit->GetIsOptimized();
421 bool Function::IsTopLevelFunction() {
424 if (Language *language = Language::FindPlugin(GetLanguage()))
425 result = language->IsTopLevelFunction(*this);
430 ConstString Function::GetDisplayName() const {
431 return m_mangled.GetDisplayDemangledName(GetLanguage());
434 CompilerDeclContext Function::GetDeclContext() {
435 ModuleSP module_sp = CalculateSymbolContextModule();
438 SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
441 SymbolFile *sym_file = sym_vendor->GetSymbolFile();
444 return sym_file->GetDeclContextForUID(GetID());
447 return CompilerDeclContext();
450 Type *Function::GetType() {
451 if (m_type == nullptr) {
454 CalculateSymbolContext(&sc);
459 SymbolVendor *sym_vendor = sc.module_sp->GetSymbolVendor();
461 if (sym_vendor == nullptr)
464 SymbolFile *sym_file = sym_vendor->GetSymbolFile();
466 if (sym_file == nullptr)
469 m_type = sym_file->ResolveTypeUID(m_type_uid);
474 const Type *Function::GetType() const { return m_type; }
476 CompilerType Function::GetCompilerType() {
477 Type *function_type = GetType();
479 return function_type->GetFullCompilerType();
480 return CompilerType();
483 uint32_t Function::GetPrologueByteSize() {
484 if (m_prologue_byte_size == 0 &&
485 m_flags.IsClear(flagsCalculatedPrologueSize)) {
486 m_flags.Set(flagsCalculatedPrologueSize);
487 LineTable *line_table = m_comp_unit->GetLineTable();
488 uint32_t prologue_end_line_idx = 0;
491 LineEntry first_line_entry;
492 uint32_t first_line_entry_idx = UINT32_MAX;
493 if (line_table->FindLineEntryByAddress(GetAddressRange().GetBaseAddress(),
495 &first_line_entry_idx)) {
496 // Make sure the first line entry isn't already the end of the prologue
497 addr_t prologue_end_file_addr = LLDB_INVALID_ADDRESS;
498 addr_t line_zero_end_file_addr = LLDB_INVALID_ADDRESS;
500 if (first_line_entry.is_prologue_end) {
501 prologue_end_file_addr =
502 first_line_entry.range.GetBaseAddress().GetFileAddress();
503 prologue_end_line_idx = first_line_entry_idx;
505 // Check the first few instructions and look for one that has
506 // is_prologue_end set to true.
507 const uint32_t last_line_entry_idx = first_line_entry_idx + 6;
508 for (uint32_t idx = first_line_entry_idx + 1;
509 idx < last_line_entry_idx; ++idx) {
510 LineEntry line_entry;
511 if (line_table->GetLineEntryAtIndex(idx, line_entry)) {
512 if (line_entry.is_prologue_end) {
513 prologue_end_file_addr =
514 line_entry.range.GetBaseAddress().GetFileAddress();
515 prologue_end_line_idx = idx;
522 // If we didn't find the end of the prologue in the line tables, then
523 // just use the end address of the first line table entry
524 if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) {
525 // Check the first few instructions and look for one that has a line
526 // number that's different than the first entry.
527 uint32_t last_line_entry_idx = first_line_entry_idx + 6;
528 for (uint32_t idx = first_line_entry_idx + 1;
529 idx < last_line_entry_idx; ++idx) {
530 LineEntry line_entry;
531 if (line_table->GetLineEntryAtIndex(idx, line_entry)) {
532 if (line_entry.line != first_line_entry.line) {
533 prologue_end_file_addr =
534 line_entry.range.GetBaseAddress().GetFileAddress();
535 prologue_end_line_idx = idx;
541 if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) {
542 prologue_end_file_addr =
543 first_line_entry.range.GetBaseAddress().GetFileAddress() +
544 first_line_entry.range.GetByteSize();
545 prologue_end_line_idx = first_line_entry_idx;
549 const addr_t func_start_file_addr =
550 m_range.GetBaseAddress().GetFileAddress();
551 const addr_t func_end_file_addr =
552 func_start_file_addr + m_range.GetByteSize();
554 // Now calculate the offset to pass the subsequent line 0 entries.
555 uint32_t first_non_zero_line = prologue_end_line_idx;
557 LineEntry line_entry;
558 if (line_table->GetLineEntryAtIndex(first_non_zero_line,
560 if (line_entry.line != 0)
563 if (line_entry.range.GetBaseAddress().GetFileAddress() >=
567 first_non_zero_line++;
570 if (first_non_zero_line > prologue_end_line_idx) {
571 LineEntry first_non_zero_entry;
572 if (line_table->GetLineEntryAtIndex(first_non_zero_line,
573 first_non_zero_entry)) {
574 line_zero_end_file_addr =
575 first_non_zero_entry.range.GetBaseAddress().GetFileAddress();
579 // Verify that this prologue end file address in the function's address
580 // range just to be sure
581 if (func_start_file_addr < prologue_end_file_addr &&
582 prologue_end_file_addr < func_end_file_addr) {
583 m_prologue_byte_size = prologue_end_file_addr - func_start_file_addr;
586 if (prologue_end_file_addr < line_zero_end_file_addr &&
587 line_zero_end_file_addr < func_end_file_addr) {
588 m_prologue_byte_size +=
589 line_zero_end_file_addr - prologue_end_file_addr;
595 return m_prologue_byte_size;
598 lldb::LanguageType Function::GetLanguage() const {
600 return m_comp_unit->GetLanguage();
602 return lldb::eLanguageTypeUnknown;
605 ConstString Function::GetName() const {
606 LanguageType language = lldb::eLanguageTypeUnknown;
608 language = m_comp_unit->GetLanguage();
609 return m_mangled.GetName(language);
612 ConstString Function::GetNameNoArguments() const {
613 LanguageType language = lldb::eLanguageTypeUnknown;
615 language = m_comp_unit->GetLanguage();
616 return m_mangled.GetName(language, Mangled::ePreferDemangledWithoutArguments);