Search code examples
c++cgcccompiler-construction

Retrieve function arguments from gcc function tree node


This question is focusing on gcc internals. I am experimenting with gcc generic trees. This small project is about compiling a hard coded front end just for education purpose. I managed to call printf externally and was able to compile an executable which is able to print a test message. The latter is proof that I manage to prepare arguments for a function. The essence of the problem is to call my own function/method and retrieve its arguments.

This is where I prepare the call:

  tree testFn;
  tree testFndeclTypeParam[] = {
                                 integer_type_node
                               };
  tree testFndeclType = build_varargs_function_type_array(integer_type_node, 1, testFndeclTypeParam);
  tree testFnDecl = build_fn_decl("testFunc", testFndeclType);
  DECL_EXTERNAL(testFnDecl) = 1;
  testFn = build1(ADDR_EXPR, build_pointer_type(testFndeclType), testFnDecl);
  tree exprTest = build_int_cst_type(integer_type_node, 20);
  tree testStmt = build_call_array_loc(UNKNOWN_LOCATION, integer_type_node, testFn, 1, testArgs);
  append_to_statement_list(testStmt, &stackStmtList);

I can confirm that the function "testFunc" is definitely called.

Now the other side, here is the function being called:

  // Built type of main "int (int)"
  tree mainFndeclTypeParam[] = {
                                 integer_type_node, // int
                               };

  tree mainFndeclType = build_function_type_array(integer_type_node, 1, mainFndeclTypeParam);
  tree mainFndecl = build_fn_decl("testFunc", mainFndeclType);  
  tree stackStmtList = alloc_stmt_list();
  tree parmList = build_decl(UNKNOWN_LOCATION, PARM_DECL, mainFndecl, integer_type_node);

I could not find an explicit example showing how to retrieve the arguments, but expected it to be in parmList, the argument tree node.


Solution

  • Here is the solution to my problem for those interested in gcc compiler design. Thanks Google or who ever maintains the Java front end.

    It should be:

    tree typelist = TYPE_ARG_TYPES(TREE_TYPE(mainFndecl));
    tree typeOfList = TREE_VALUE(typelist);
    tree parmList = build_decl(UNKNOWN_LOCATION, PARM_DECL, NULL_TREE, typeOfList);
    tree *ptr = &DECL_ARGUMENTS(mainFndecl);
    *ptr = parmList;
    

    The next argument can be retrieved by using TREE_CHAIN, if any.