1//===- ExtractFunction.cpp - Extract a function from Program --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements several methods that are used to extract functions,
11// loops, or portions of a module from the rest of the module.
12//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/LLVMContext.h"
19#include "llvm/Module.h"
20#include "llvm/PassManager.h"
21#include "llvm/Pass.h"
22#include "llvm/Analysis/Verifier.h"
23#include "llvm/Assembly/Writer.h"
24#include "llvm/Transforms/IPO.h"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/Utils/Cloning.h"
27#include "llvm/Transforms/Utils/FunctionUtils.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/FileUtilities.h"
32#include "llvm/Support/ToolOutputFile.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/Signals.h"
35#include <set>
36using namespace llvm;
37
38namespace llvm {
39  bool DisableSimplifyCFG = false;
40  extern cl::opt<std::string> OutputPrefix;
41} // End llvm namespace
42
43namespace {
44  cl::opt<bool>
45  NoDCE ("disable-dce",
46         cl::desc("Do not use the -dce pass to reduce testcases"));
47  cl::opt<bool, true>
48  NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
49         cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
50}
51
52/// deleteInstructionFromProgram - This method clones the current Program and
53/// deletes the specified instruction from the cloned module.  It then runs a
54/// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
55/// depends on the value.  The modified module is then returned.
56///
57Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
58                                                unsigned Simplification) {
59  // FIXME, use vmap?
60  Module *Clone = CloneModule(Program);
61
62  const BasicBlock *PBB = I->getParent();
63  const Function *PF = PBB->getParent();
64
65  Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn
66  std::advance(RFI, std::distance(PF->getParent()->begin(),
67                                  Module::const_iterator(PF)));
68
69  Function::iterator RBI = RFI->begin();  // Get iterator to corresponding BB
70  std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
71
72  BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
73  std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
74  Instruction *TheInst = RI;              // Got the corresponding instruction!
75
76  // If this instruction produces a value, replace any users with null values
77  if (!TheInst->getType()->isVoidTy())
78    TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
79
80  // Remove the instruction from the program.
81  TheInst->getParent()->getInstList().erase(TheInst);
82
83  // Spiff up the output a little bit.
84  std::vector<std::string> Passes;
85
86  /// Can we get rid of the -disable-* options?
87  if (Simplification > 1 && !NoDCE)
88    Passes.push_back("dce");
89  if (Simplification && !DisableSimplifyCFG)
90    Passes.push_back("simplifycfg");      // Delete dead control flow
91
92  Passes.push_back("verify");
93  Module *New = runPassesOn(Clone, Passes);
94  delete Clone;
95  if (!New) {
96    errs() << "Instruction removal failed.  Sorry. :(  Please report a bug!\n";
97    exit(1);
98  }
99  return New;
100}
101
102/// performFinalCleanups - This method clones the current Program and performs
103/// a series of cleanups intended to get rid of extra cruft on the module
104/// before handing it to the user.
105///
106Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
107  // Make all functions external, so GlobalDCE doesn't delete them...
108  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
109    I->setLinkage(GlobalValue::ExternalLinkage);
110
111  std::vector<std::string> CleanupPasses;
112  CleanupPasses.push_back("globaldce");
113
114  if (MayModifySemantics)
115    CleanupPasses.push_back("deadarghaX0r");
116  else
117    CleanupPasses.push_back("deadargelim");
118
119  Module *New = runPassesOn(M, CleanupPasses);
120  if (New == 0) {
121    errs() << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
122    return M;
123  }
124  delete M;
125  return New;
126}
127
128
129/// ExtractLoop - Given a module, extract up to one loop from it into a new
130/// function.  This returns null if there are no extractable loops in the
131/// program or if the loop extractor crashes.
132Module *BugDriver::ExtractLoop(Module *M) {
133  std::vector<std::string> LoopExtractPasses;
134  LoopExtractPasses.push_back("loop-extract-single");
135
136  Module *NewM = runPassesOn(M, LoopExtractPasses);
137  if (NewM == 0) {
138    outs() << "*** Loop extraction failed: ";
139    EmitProgressBitcode(M, "loopextraction", true);
140    outs() << "*** Sorry. :(  Please report a bug!\n";
141    return 0;
142  }
143
144  // Check to see if we created any new functions.  If not, no loops were
145  // extracted and we should return null.  Limit the number of loops we extract
146  // to avoid taking forever.
147  static unsigned NumExtracted = 32;
148  if (M->size() == NewM->size() || --NumExtracted == 0) {
149    delete NewM;
150    return 0;
151  } else {
152    assert(M->size() < NewM->size() && "Loop extract removed functions?");
153    Module::iterator MI = NewM->begin();
154    for (unsigned i = 0, e = M->size(); i != e; ++i)
155      ++MI;
156  }
157
158  return NewM;
159}
160
161
162// DeleteFunctionBody - "Remove" the function by deleting all of its basic
163// blocks, making it external.
164//
165void llvm::DeleteFunctionBody(Function *F) {
166  // delete the body of the function...
167  F->deleteBody();
168  assert(F->isDeclaration() && "This didn't make the function external!");
169}
170
171/// GetTorInit - Given a list of entries for static ctors/dtors, return them
172/// as a constant array.
173static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
174  assert(!TorList.empty() && "Don't create empty tor list!");
175  std::vector<Constant*> ArrayElts;
176  Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext());
177
178  StructType *STy =
179    StructType::get(Int32Ty, TorList[0].first->getType(), NULL);
180  for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
181    Constant *Elts[] = {
182      ConstantInt::get(Int32Ty, TorList[i].second),
183      TorList[i].first
184    };
185    ArrayElts.push_back(ConstantStruct::get(STy, Elts));
186  }
187  return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(),
188                                           ArrayElts.size()),
189                            ArrayElts);
190}
191
192/// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
193/// M1 has all of the global variables.  If M2 contains any functions that are
194/// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
195/// prune appropriate entries out of M1s list.
196static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
197                                ValueToValueMapTy &VMap) {
198  GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
199  if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
200      !GV->use_empty()) return;
201
202  std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
203  ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
204  if (!InitList) return;
205
206  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
207    if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
208      if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
209
210      if (CS->getOperand(1)->isNullValue())
211        break;  // Found a null terminator, stop here.
212
213      ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
214      int Priority = CI ? CI->getSExtValue() : 0;
215
216      Constant *FP = CS->getOperand(1);
217      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
218        if (CE->isCast())
219          FP = CE->getOperand(0);
220      if (Function *F = dyn_cast<Function>(FP)) {
221        if (!F->isDeclaration())
222          M1Tors.push_back(std::make_pair(F, Priority));
223        else {
224          // Map to M2's version of the function.
225          F = cast<Function>(VMap[F]);
226          M2Tors.push_back(std::make_pair(F, Priority));
227        }
228      }
229    }
230  }
231
232  GV->eraseFromParent();
233  if (!M1Tors.empty()) {
234    Constant *M1Init = GetTorInit(M1Tors);
235    new GlobalVariable(*M1, M1Init->getType(), false,
236                       GlobalValue::AppendingLinkage,
237                       M1Init, GlobalName);
238  }
239
240  GV = M2->getNamedGlobal(GlobalName);
241  assert(GV && "Not a clone of M1?");
242  assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
243
244  GV->eraseFromParent();
245  if (!M2Tors.empty()) {
246    Constant *M2Init = GetTorInit(M2Tors);
247    new GlobalVariable(*M2, M2Init->getType(), false,
248                       GlobalValue::AppendingLinkage,
249                       M2Init, GlobalName);
250  }
251}
252
253
254/// SplitFunctionsOutOfModule - Given a module and a list of functions in the
255/// module, split the functions OUT of the specified module, and place them in
256/// the new module.
257Module *
258llvm::SplitFunctionsOutOfModule(Module *M,
259                                const std::vector<Function*> &F,
260                                ValueToValueMapTy &VMap) {
261  // Make sure functions & globals are all external so that linkage
262  // between the two modules will work.
263  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
264    I->setLinkage(GlobalValue::ExternalLinkage);
265  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
266       I != E; ++I) {
267    if (I->hasName() && I->getName()[0] == '\01')
268      I->setName(I->getName().substr(1));
269    I->setLinkage(GlobalValue::ExternalLinkage);
270  }
271
272  ValueToValueMapTy NewVMap;
273  Module *New = CloneModule(M, NewVMap);
274
275  // Make sure global initializers exist only in the safe module (CBE->.so)
276  for (Module::global_iterator I = New->global_begin(), E = New->global_end();
277       I != E; ++I)
278    I->setInitializer(0);  // Delete the initializer to make it external
279
280  // Remove the Test functions from the Safe module
281  std::set<Function *> TestFunctions;
282  for (unsigned i = 0, e = F.size(); i != e; ++i) {
283    Function *TNOF = cast<Function>(VMap[F[i]]);
284    DEBUG(errs() << "Removing function ");
285    DEBUG(WriteAsOperand(errs(), TNOF, false));
286    DEBUG(errs() << "\n");
287    TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
288    DeleteFunctionBody(TNOF);       // Function is now external in this module!
289  }
290
291
292  // Remove the Safe functions from the Test module
293  for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
294    if (!TestFunctions.count(I))
295      DeleteFunctionBody(I);
296
297
298  // Make sure that there is a global ctor/dtor array in both halves of the
299  // module if they both have static ctor/dtor functions.
300  SplitStaticCtorDtor("llvm.global_ctors", M, New, NewVMap);
301  SplitStaticCtorDtor("llvm.global_dtors", M, New, NewVMap);
302
303  return New;
304}
305
306//===----------------------------------------------------------------------===//
307// Basic Block Extraction Code
308//===----------------------------------------------------------------------===//
309
310/// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
311/// into their own functions.  The only detail is that M is actually a module
312/// cloned from the one the BBs are in, so some mapping needs to be performed.
313/// If this operation fails for some reason (ie the implementation is buggy),
314/// this function should return null, otherwise it returns a new Module.
315Module *BugDriver::ExtractMappedBlocksFromModule(const
316                                                 std::vector<BasicBlock*> &BBs,
317                                                 Module *M) {
318  sys::Path uniqueFilename(OutputPrefix + "-extractblocks");
319  std::string ErrMsg;
320  if (uniqueFilename.createTemporaryFileOnDisk(true, &ErrMsg)) {
321    outs() << "*** Basic Block extraction failed!\n";
322    errs() << "Error creating temporary file: " << ErrMsg << "\n";
323    EmitProgressBitcode(M, "basicblockextractfail", true);
324    return 0;
325  }
326  sys::RemoveFileOnSignal(uniqueFilename);
327
328  std::string ErrorInfo;
329  tool_output_file BlocksToNotExtractFile(uniqueFilename.c_str(), ErrorInfo);
330  if (!ErrorInfo.empty()) {
331    outs() << "*** Basic Block extraction failed!\n";
332    errs() << "Error writing list of blocks to not extract: " << ErrorInfo
333           << "\n";
334    EmitProgressBitcode(M, "basicblockextractfail", true);
335    return 0;
336  }
337  for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
338       I != E; ++I) {
339    BasicBlock *BB = *I;
340    // If the BB doesn't have a name, give it one so we have something to key
341    // off of.
342    if (!BB->hasName()) BB->setName("tmpbb");
343    BlocksToNotExtractFile.os() << BB->getParent()->getNameStr() << " "
344                                << BB->getName() << "\n";
345  }
346  BlocksToNotExtractFile.os().close();
347  if (BlocksToNotExtractFile.os().has_error()) {
348    errs() << "Error writing list of blocks to not extract: " << ErrorInfo
349           << "\n";
350    EmitProgressBitcode(M, "basicblockextractfail", true);
351    BlocksToNotExtractFile.os().clear_error();
352    return 0;
353  }
354  BlocksToNotExtractFile.keep();
355
356  std::string uniqueFN = "--extract-blocks-file=" + uniqueFilename.str();
357  const char *ExtraArg = uniqueFN.c_str();
358
359  std::vector<std::string> PI;
360  PI.push_back("extract-blocks");
361  Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
362
363  uniqueFilename.eraseFromDisk(); // Free disk space
364
365  if (Ret == 0) {
366    outs() << "*** Basic Block extraction failed, please report a bug!\n";
367    EmitProgressBitcode(M, "basicblockextractfail", true);
368  }
369  return Ret;
370}
371