I want to write a simple frontend for language PL/0,the lexer and parser seems work well,but there has a bug when generating call statement LLVM IR.
Here is my code for generating IR for the PL/0 call statement: CALL ident. It fails to execute the Builder.CreateCall(F,None,"calltmp");
The console says:
pl0: /root/llvm-6.0/lib/IR/Value.cpp:247:
void llvm::Value::setNameImpl(const llvm::Twine&):
Assertion `!getType()->isVoidTy() && "Cannot assign a name to void values!"' failed.
Aborted (core dumped)
The TheModule->getFunction() gets the correct function. All functions in my implementation has function type void ..(), no return value and no argument.
I tried to debug it with gdb; it seems the instruction created by Builder.CreateCall(...) is "optimized out".
What's wrong with this?
Code for generating call statement:
bool CallStatAST::codegen()
{
auto F = TheModule->getFunction(Callee);
if(!F)
logErrorL("Failing to get function from module at CallStatAST::codegen()!\n");
//std::vector<Value*> Args;
Builder.CreateCall(F,None,"calltmp");
return true;
}
gdb debug information:
1. (gdb) break 391
Breakpoint 1 at 0x4713a5: file pl0.cpp, line 391.
2. (gdb) run < test1.pl0
Starting program: /root/my_llvm/PL0/pl0 < test1.pl0
3. Breakpoint 1, get (this=optimized out) at /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../include/c++/4.8.5/bits/unique_ptr.h:234
234 { return std::get<0>(_M_t); }
4. (gdb) n
CallStatAST::codegen (this=0xa165d0) at pl0.cpp:392
392 auto F = TheModule->getFunction(Callee);
5. (gdb) p F->dump()
define internal void #myfun()
{
entry:
%i = alloca double
%a = load double, double* #a
%b = load double, double* #b
%addtmp = fadd double %a, %b
store double %addtmp, double* %i
ret void
}
$1 = void
6. (gdb) p F->getName()
$2 = {static npos = 18446744073709551615, Data = 0xa17310 "myfun", Length = 5}
(gdb) n
397 Builder.CreateCall(F,None,"calltmp");
7. (gdb) s
Twine (Str=0xa17278 "\300P\241", this=optimized out) at /usr/local/include/llvm/ADT/Twine.h:270
270 LHS.cString = Str;
8. (gdb) n
CallStatAST::codegen (this=optimized out) at pl0.cpp:397
397 Builder.CreateCall(F,None,"calltmp");
How fool I am!
I unbelievable want to assign a name to a void return value,there does not have a value and how can set a name for it?
convert:
Builder.CreateCall(F,None,"calltmp");
to:
Builder.CreateCall(F,None);
all things work again!
Related
I am trying to insert function call inside a main function, so then when i run generated binary file, function will be executed automatically. Since language i am trying to "compile" looks like a "scripted" language :
function foo () begin 3 end;
function boo () begin 4 end;
writeln (foo()+boo()) ;
writeln (8) ;
writeln (9) ;
where writeln is a function available by default, and after executing binary i expect to see 7 8 9. Is there a way to insert last function call right before return statement of a main function ?
Right now I have
define i32 #main() {
entry:
ret i32 0
}
and i want to have something like
define i32 #main() {
entry:
%calltmp = call double #writeln(double 7.000000e+00)
%calltmp = call double #writeln(double 8.000000e+00)
%calltmp = call double #writeln(double 9.000000e+00)
ret i32 0
}
editing IR file manually and compile it afterwards works, but i want to do it in codegen part of my code.
edit
what i generate right now is
define double #__anon_expr() {
entry:
%main = call double #writeln(double 3.000000e+00)
ret double %main
}
define i32 #main() {
entry:
ret i32 0
}
so when i execute binary - nothing happens
feel free to source your inspiration from here
Type * returnType = Type::getInt32Ty(TheContext);
std::vector<Type *> argTypes;
FunctionType * functionType = FunctionType::get(returnType, argTypes, false);
Function * function = Function::Create(functionType, Function::ExternalLinkage, "main", TheModule.get());
BasicBlock * BB = BasicBlock::Create(TheContext, "entry", function);
Builder.SetInsertPoint(BB);
vector<Value *> args;
args.push_back(ConstantFP::get(TheContext, APFloat(4.0)));
Builder.CreateCall(getFunction("writeln"), args, "call");
Value * returnValue = Builder.getInt32(0);
Builder.CreateRet(returnValue);
I debug Chrome in gdb and I run into this problem all the time:
If I try to print a variable of certain type, GDB does not know its internals:
(gdb) p current_child_.get()
$12 = (blink::NGBlockNode *) 0xc2f755c1830
(gdb) p *(current_child_.get())
$13 = <incomplete type>
But, if I just set a breakpoint in a constructor of that class, gdb will suddenly discover that type's symbols:
(gdb) br blink::NGBlockNode::NGBlockNode
Breakpoint 3 at 0x51db40 (4 locations)
(gdb) p *(current_child_.get())
$14 = {
<blink::NGLayoutInputNode> = {
<blink::GarbageCollectedFinalized<blink::NGLayoutInputNode>> = {
<blink::GarbageCollected<blink::NGLayoutInputNode>> = {<No data fields>}, <No data fields>},
This is so annoying, I have a set of macros to set breakpoints in classes I usually print. Are there any other workarounds?
I know one workaround. If you know the file which defines the type, you can force loading debug information of that type, by "print 'file.cc'::some_variable". If this "some_variable" actually exists or not does not really matter.
e.g.
(gdb) p render_thread
$2 = (content::RenderThreadImpl *) 0x1261201f7920
(gdb) p *render_thread
$3 = <incomplete type>
(gdb) ptype render_thread
type = class content::RenderThreadImpl {
<incomplete type>
} *
(gdb) p 'render_thread_impl.cc'::nonexist_variable
No symbol "nonexist_variable" in specified context.
(gdb) ptype render_thread
type = /* real type = content::RenderThreadImpl * */
class content::RenderThreadImpl : <snipped> {
<snipped>
} *
(gdb) p *render_thread
$4 = (content::RenderThreadImpl) { <snipped> }
(gdb)
Turns out that the root cause is my compile flags: using gcc --gdb-index and --split-dwarf options together results in corrupt debug information. – Aleksandar Totic
I have got executable module iCoreTest.exe, wich dynamicly loaded library IRTest.rs. I want to debug it via lldb c++ api.
When I create "iCoreTest.exe" process under lldb throug lldb::SBTarget::Launch(..); everything works fine. With fine, I mean I can set breakpoints BreakpointCreateByLocation and when the debugger stops on it get the event from SBListener.WaitForEvent();
Problems begins when I want to attach to the currently running process.
Create target and attach to process
m_debugData->currentTarget=m_debugData>debugger.CreateTarget(executable.c_str());
m_debugData->currentProcess = m_debugData>currentTarget.AttachToProcessWithName(m_debugData->listener, processName.c_str(), false, error);
Load module "IRTest.rs"
auto module = m_debugData->currentTarget.AddModule("IRTest.rs", "i386-pc-windows-msvc", nullptr);
After that lldb stops on "ntdll.dll`DbgBreakPoint + 1"
I execute command m_debugData->currentProcess.Continue();
So, ICoreTest.exe is running..
Add breakpoint m_debugData->currentTarget.BreakpointCreateByLocation("IRTest.st", 58);
The added breakpoint does not triggered
After this I print the existing breakpoints using the following code:
void LLDBRunner::printBreakpoints()
{
for (int i = 0; i < m_debugData->currentTarget.GetNumBreakpoints(); i++)
{
auto bp = m_debugData->currentTarget.GetBreakpointAtIndex(i);
for (int j = 0; j < bp.GetNumLocations(); j++)
{
auto loc = bp.GetLocationAtIndex(j);
lldb::SBStream stream;
loc.GetDescription(stream, lldb::DescriptionLevel::eDescriptionLevelFull);
auto str = stream.GetData();
}
}
}
And output was:
1.1: where = IRTest.rs`Add + 421 at IRTest.st:58, address = IRTest.rs[0x10001525], unresolved, hit count = 0
Which means my breakpoint is unresolved..Why? :)
Also!
When i use lldb command line breakpoint is resolved, and working:
(lldb) attach -p 17448
Process 17448 stopped
* thread #1: tid = 0x0ae0, 0x77bc8d21 ntdll.dll`DbgBreakPoint + 1, stop reason = Exception 0x80000003 encountered at address 0x77bc8d20
frame #0: 0x77bc8d21 ntdll.dll`DbgBreakPoint + 1
ntdll.dll`DbgBreakPoint:
-> 0x77bc8d21 <+1>: retl
0x77bc8d22 <+2>: int3
0x77bc8d23 <+3>: int3
0x77bc8d24 <+4>: int3
Executable module set to "iCoreTest.exe".
Architecture set to: i386-pc-windows-msvc.
(lldb) b IRTest.st:58
Breakpoint 1: where = IRTest.rs`Add + 421 at IRTest.st:58, address = 0x07ca1525
(lldb) b
Current breakpoints:
1: file = 'IRTest.st', line = 58, exact_match = 0, locations = 1, resolved = 1, hit count = 0
1.1: where = IRTest.rs`Add + 421 at IRTest.st:58, address = 0x07ca1525, resolved, hit count = 0
(lldb) c
Process 17448 resuming
Process 17448 stopped
* thread #6: tid = 0x2560, 0x07ca1525 IRTest.rs`Add(X1=2, X2=42, X3=(RANGE = 1, MIN_SCALE = -4095, MAX_SCALE = 4095)) + 421 at IRTest.st:58, stop reason = breakpoint 1.1
frame #0: 0x07ca1525 IRTest.rs`Add(X1=2, X2=42, X3=(RANGE = 1, MIN_SCALE = -4095, MAX_SCALE = 4095)) + 421 at IRTest.st:58
55 i, j : INT;
56 END_VAR
57
-> 58 tmpInteg();
59
60
61
(lldb)
UPDATE:
I write a simple program wich reproduce bug
prog.cpp:
#include <cstdio>
void doSomething(void);
void doSomething(void)
{
int loop = 0;
loop += 1;
loop += 2;
loop += 3;
}
int main(void)`
{
printf("start \n");
while(1)
{
doSomething();
}
return 0;
}
Compile it..
gcc prog.cpp -g -O0
When i`m trying to set break point
m_debugData->currentTarget.BreakpointCreateByLocation("prog.cpp", 7);
I get same result
1.1: where = a.exe`doSomething() + 6 at prog.cpp:7, address = a.exe[0x00401356], unresolved, hit count = 0
My little research:
I compare lldb behavior in two versions:
Launch new process(is ok)
Attach to process(broken)
I found that in method
lldb::break_id_t
Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
line..
load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
return LLDB_INVALID_ADDRESS in version when I attach to process.
CallStack:
liblldb.dll!lldb_private::Process::CreateBreakpointSite(const std::shared_ptr<lldb_private::BreakpointLocation> & owner, bool use_hardware) Line 2094 C++
liblldb.dll!lldb_private::BreakpointLocation::ResolveBreakpointSite() Line 523 C++
liblldb.dll!lldb_private::BreakpointLocationList::AddLocation(const lldb_private::Address & addr, bool resolve_indirect_symbols, bool * new_location) Line 254 C++
liblldb.dll!lldb_private::Breakpoint::AddLocation(const lldb_private::Address & addr, bool * new_location) Line 102 C++
liblldb.dll!lldb_private::BreakpointResolver::AddLocation(lldb_private::Address loc_addr, bool * new_location) Line 214 C++
liblldb.dll!lldb_private::BreakpointResolver::SetSCMatchesByLine(lldb_private::SearchFilter & filter, lldb_private::SymbolContextList & sc_list, bool skip_prologue, const char * log_ident) Line 184 C++
liblldb.dll!lldb_private::BreakpointResolverFileLine::SearchCallback(lldb_private::SearchFilter & filter, lldb_private::SymbolContext & context, lldb_private::Address * addr, bool containing) Line 94 C++
liblldb.dll!lldb_private::SearchFilter::DoModuleIteration(const lldb_private::SymbolContext & context, lldb_private::Searcher & searcher) Line 190 C++
liblldb.dll!lldb_private::SearchFilter::Search(lldb_private::Searcher & searcher) Line 118 C++
liblldb.dll!lldb_private::BreakpointResolver::ResolveBreakpoint(lldb_private::SearchFilter & filter) Line 62 C++
liblldb.dll!lldb_private::Breakpoint::ResolveBreakpoint() Line 355 C++
liblldb.dll!lldb_private::Target::AddBreakpoint(std::shared_ptr<lldb_private::Breakpoint> bp_sp, bool internal) Line 695 C++
liblldb.dll!lldb_private::Target::CreateBreakpoint(std::shared_ptr<lldb_private::SearchFilter> & filter_sp, std::shared_ptr<lldb_private::BreakpointResolver> & resolver_sp, bool internal, bool request_hardware, bool resolve_indirect_symbols) Line 672 C++
liblldb.dll!lldb_private::Target::CreateBreakpoint(const lldb_private::FileSpecList * containingModules, const lldb_private::FileSpec & file, unsigned int line_no, unsigned __int64 offset, lldb_private::LazyBool check_inlines, lldb_private::LazyBool skip_prologue, bool internal, bool hardware, lldb_private::LazyBool move_to_nearest_code) Line 411 C++
liblldb.dll!lldb::SBTarget::BreakpointCreateByLocation(const lldb::SBFileSpec & sb_file_spec, unsigned int line, unsigned __int64 offset) Line 832 C++
liblldb.dll!lldb::SBTarget::BreakpointCreateByLocation(const lldb::SBFileSpec & sb_file_spec, unsigned int line) Line 803 C++
liblldb.dll!lldb::SBTarget::BreakpointCreateByLocation(const char * file, unsigned int line) Line 796 C++
ConsoleApplication1.exe!Debugger::LLDBRunner::setBreakpoint(std::basic_string<char,std::char_traits<char>,std::allocator<char> > file, unsigned int line) Line 204 C++
ConsoleApplication1.exe!main() Line 28 C++
UPDATE 2:
I print 'a.exe' module sections using the following code:
for (int i = 0; i < m_debugData->currentTarget.GetNumModules(); i++)
{
auto module = m_debugData->currentTarget.GetModuleAtIndex(i);
auto moduleName = module.GetFileSpec().GetFilename();
for (int j = 0; j < module.GetNumSections(); j++)
{
auto section = module.GetSectionAtIndex(j);
auto sectionName = section.GetName();
auto addr = section.GetLoadAddress(m_debugData->currentTarget);
auto isValid = LLDB_INVALID_ADDRESS != addr;
std::cout << "Module: " << moduleName << "; Section: " << sectionName << "; IsValid: " << isValid << std::endl;
}
}
An output was:
State changed unknown->stopped
Module: a.exe; Section: .text; IsValid: 0
Module: a.exe; Section: .data; IsValid: 0
Module: a.exe; Section: .rdata; IsValid: 0
Module: a.exe; Section: .eh_frame; IsValid: 0
Module: a.exe; Section: .bss; IsValid: 0
Module: a.exe; Section: .idata; IsValid: 0
Module: a.exe; Section: .CRT; IsValid: 0
Module: a.exe; Section: .tls; IsValid: 0
Module: a.exe; Section: .debug_aranges; IsValid: 0
Module: a.exe; Section: .debug_info; IsValid: 0
Module: a.exe; Section: .debug_abbrev; IsValid: 0
Module: a.exe; Section: .debug_line; IsValid: 0
Module: a.exe; Section: .debug_frame; IsValid: 0
It's hard to say with certainty, but the python APIs and the command line apis are not entirely the same. They both have their own set of things they do internally before running the "actual" command you requested. Debugging on Windows is definitely not as mature as on other platforms, in part because there are not a lot of people using it yet. I would suggest reporting this as a bug on the lldb bug tracker.
In the meantime, maybe you can try creating a target manually, and setting the breakpoint BEFORE you attach to the process. I don't know if this will work, but resolving a breakpoint dynamically when a module is loaded, versus trying to resolve it immediately when you drop the breakpoint down are two different codepaths, so it's possible it will work if the breakpoint is already there.
I am trying to write a simple interpreter.
I am trying to generate LLVM IR for assignment operation. The code for the generation part looks like this
llvm::Value* codeGenSymTab(llvm::LLVMContext& context) {
printf("\n CodeGen SymTab \n");
Value *num = ConstantInt::get(Type::getInt64Ty(context), aTable.value, true);
Value *alloc = new AllocaInst(IntegerType::get(context, 32), aTable.variableName,entry);
StoreInst *ptr = new StoreInst(num,alloc,false,entry);
}
Here goes the SymTab definition:
struct SymTab {
char* variableName;
int value;
llvm::Value* (*codeGen)(llvm::LLVMContext& context);
};
When I try to execute the output file,I get the following error:
Assertion failed: (getOperand(0)->getType() == cast<PointerType>(getOperand(1)->getType())->getElementType() && "Ptr must be a pointer to Val type!"), function AssertOK, file Instructions.cpp, line 1084.
Abort trap: 6
Can you help me resolve it ?
Thanks
You try to store a value of type i64 into an address of type i32*, and these don't match.
You can fix this by using the same type - or preferably, the actual same object:
IntegerType *int_type = Type::getInt64Ty(context);
Value *num = ConstantInt::get(int_type, aTable.value, true);
Value *alloc = new AllocaInst(int_type, aTable.variableName, entry);
StoreInst *ptr = new StoreInst(num,alloc,false,entry);
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.
TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true); /* col = 0x0 */
i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?
gdb proof:
151 col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
<Gtk::Object> = {
<Glib::Object> = {
<Glib::ObjectBase> = <invalid address>,
members of Glib::Object:
_vptr$Object = 0x7fff5fc06a20,
static object_class_ = {<No data fields>}
},
members of Gtk::Object:
static object_class_ = {<No data fields>},
referenced_ = 21,
gobject_disposed_ = 60
},
members of Gtk::TreeViewColumn:
static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152 col->set_resizable(true); /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()
i have no idea what causes this phenomenon. do you have?
Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.
The function call:
preview->get_column(pcFolder);
returns NULL.
When gdb shows the current code line, it hasn't been executed until you type next.
You probably pass an index that is larger than the number of columns in preview. Try:
p pcFolder
p preview->get_columns().size()
preview->get_column(); returns NULL, before that, its just some random value, since you didn't initialize the col variable
Better code would actually be to initialise the variable immediately on use by calling getColumn at the point of declaration:
TreeViewColumn *col = preview->get_column(pcFolder);
If this function can return NULL (as it appears to) you must then check before you use the pointer, thus:
if( col != NULL )
{
col->set_resizable( true );
}
// else handle the "error" if you want
preview->get_column(pcFolder)
must be returning 0.