0

I have a file in which the main function calls three test functions, namely, test 1, test 2 and test 3. I want to make a pass that deletes each two of the functions one by one and returns the file that's calling only one of the three test functions. Right now, my pass is a ModulePass with this body:

 for(Module::iterator F= M.begin(), E = M.end(); F != E; ++F) // iterating over functions in a module
    {
            std::string function_name = F->getName();   
            if((std::find(calledFunctions.begin(), calledFunctions.end(), function_name) != calledFunctions.end())
                    && function_name != current_function ) 
            {
                F->replaceAllUsesWith(UndefValue::get(F->getType()));
                F->removeFromParent(); 
            }
    }

where called functions contain the functions you want gone (say, test 2 and test 3) and current_function is the one you want in the main function (test 1 in this case)

Can someone please tell me if my approach is right? As of now, I'm getting a segmentation fault.

mikasa
  • 783
  • 1
  • 11
  • 29
  • Deleting a function invalidates `Module::iterator F`, I suspect. Try deleting all functions after the loop. – arrowd Apr 04 '18 at 11:22
  • Yes thats what i did later on. The pass works fine but when I run the bitcode i get it gives me a segmentation fault when it tries to execute the line where I replaced the function call with undef. The exact line where it fails is: `invoke.cont1: ; preds = %invoke.cont invoke void undef() to label %invoke.cont3 unwind label %lpad` where cont3 basically prints out "done" (which it's not doing so rn). – mikasa Apr 04 '18 at 13:18
  • I believe its giving me a segmentation fault because at the line mentioned above, it is trying to read from an uninitialized memory (got it from google that undef was created to represent uninitialized memory reads). This leads me to believe that perhaps I should be replacing my functions calls with something else. Can you please suggest where I can go from here? – mikasa Apr 04 '18 at 20:56
  • I suggest you using a debugger to find out exact cause, not make guesses. – arrowd Apr 05 '18 at 08:04

1 Answers1

0

You need to delete the invoke/call Instructions referencing your deleted function instead of replacing them with UndefinedValue. This could be achieved from iterating the function's Def-Use Chain and delete Values accordingly

Zhang HanSheng
  • 342
  • 1
  • 13