xref: /src/contrib/llvm-project/llvm/tools/bugpoint/ExtractFunction.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1009b1c42SEd Schouten //===- ExtractFunction.cpp - Extract a function from Program --------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements several methods that are used to extract functions,
10009b1c42SEd Schouten // loops, or portions of a module from the rest of the module.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14009b1c42SEd Schouten #include "BugDriver.h"
154a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
164a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
174a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
184a16efa3SDimitry Andric #include "llvm/IR/LLVMContext.h"
195a5ac124SDimitry Andric #include "llvm/IR/LegacyPassManager.h"
204a16efa3SDimitry Andric #include "llvm/IR/Module.h"
215ca98fd9SDimitry Andric #include "llvm/IR/Verifier.h"
224a16efa3SDimitry Andric #include "llvm/Pass.h"
234a16efa3SDimitry Andric #include "llvm/Support/CommandLine.h"
244a16efa3SDimitry Andric #include "llvm/Support/Debug.h"
254a16efa3SDimitry Andric #include "llvm/Support/FileUtilities.h"
264a16efa3SDimitry Andric #include "llvm/Support/Path.h"
274a16efa3SDimitry Andric #include "llvm/Support/Signals.h"
284a16efa3SDimitry Andric #include "llvm/Support/ToolOutputFile.h"
29009b1c42SEd Schouten #include "llvm/Transforms/IPO.h"
30009b1c42SEd Schouten #include "llvm/Transforms/Scalar.h"
31009b1c42SEd Schouten #include "llvm/Transforms/Utils/Cloning.h"
3258b69754SDimitry Andric #include "llvm/Transforms/Utils/CodeExtractor.h"
33009b1c42SEd Schouten #include <set>
34009b1c42SEd Schouten using namespace llvm;
35009b1c42SEd Schouten 
365ca98fd9SDimitry Andric #define DEBUG_TYPE "bugpoint"
375ca98fd9SDimitry Andric 
38009b1c42SEd Schouten namespace llvm {
39009b1c42SEd Schouten bool DisableSimplifyCFG = false;
4059850d08SRoman Divacky extern cl::opt<std::string> OutputPrefix;
41009b1c42SEd Schouten } // End llvm namespace
42009b1c42SEd Schouten 
43009b1c42SEd Schouten namespace {
44b915e9e0SDimitry Andric cl::opt<bool> NoDCE("disable-dce",
45009b1c42SEd Schouten                     cl::desc("Do not use the -dce pass to reduce testcases"));
46009b1c42SEd Schouten cl::opt<bool, true>
47009b1c42SEd Schouten     NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
48009b1c42SEd Schouten            cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
4963faed5bSDimitry Andric 
globalInitUsesExternalBA(GlobalVariable * GV)5063faed5bSDimitry Andric Function *globalInitUsesExternalBA(GlobalVariable *GV) {
5163faed5bSDimitry Andric   if (!GV->hasInitializer())
525ca98fd9SDimitry Andric     return nullptr;
5363faed5bSDimitry Andric 
5463faed5bSDimitry Andric   Constant *I = GV->getInitializer();
5563faed5bSDimitry Andric 
5663faed5bSDimitry Andric   // walk the values used by the initializer
5763faed5bSDimitry Andric   // (and recurse into things like ConstantExpr)
5863faed5bSDimitry Andric   std::vector<Constant *> Todo;
5963faed5bSDimitry Andric   std::set<Constant *> Done;
6063faed5bSDimitry Andric   Todo.push_back(I);
6163faed5bSDimitry Andric 
6263faed5bSDimitry Andric   while (!Todo.empty()) {
6363faed5bSDimitry Andric     Constant *V = Todo.back();
6463faed5bSDimitry Andric     Todo.pop_back();
6563faed5bSDimitry Andric     Done.insert(V);
6663faed5bSDimitry Andric 
6763faed5bSDimitry Andric     if (BlockAddress *BA = dyn_cast<BlockAddress>(V)) {
6863faed5bSDimitry Andric       Function *F = BA->getFunction();
6963faed5bSDimitry Andric       if (F->isDeclaration())
7063faed5bSDimitry Andric         return F;
71009b1c42SEd Schouten     }
72009b1c42SEd Schouten 
7363faed5bSDimitry Andric     for (User::op_iterator i = V->op_begin(), e = V->op_end(); i != e; ++i) {
7463faed5bSDimitry Andric       Constant *C = dyn_cast<Constant>(*i);
7563faed5bSDimitry Andric       if (C && !isa<GlobalValue>(C) && !Done.count(C))
7663faed5bSDimitry Andric         Todo.push_back(C);
7763faed5bSDimitry Andric     }
7863faed5bSDimitry Andric   }
795ca98fd9SDimitry Andric   return nullptr;
8063faed5bSDimitry Andric }
8163faed5bSDimitry Andric } // end anonymous namespace
8263faed5bSDimitry Andric 
8367c32a98SDimitry Andric std::unique_ptr<Module>
deleteInstructionFromProgram(const Instruction * I,unsigned Simplification)8467c32a98SDimitry Andric BugDriver::deleteInstructionFromProgram(const Instruction *I,
85d39c594dSDimitry Andric                                         unsigned Simplification) {
86d39c594dSDimitry Andric   // FIXME, use vmap?
87eb11fae6SDimitry Andric   std::unique_ptr<Module> Clone = CloneModule(*Program);
88009b1c42SEd Schouten 
89009b1c42SEd Schouten   const BasicBlock *PBB = I->getParent();
90009b1c42SEd Schouten   const Function *PF = PBB->getParent();
91009b1c42SEd Schouten 
92d39c594dSDimitry Andric   Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn
93b915e9e0SDimitry Andric   std::advance(
94b915e9e0SDimitry Andric       RFI, std::distance(PF->getParent()->begin(), Module::const_iterator(PF)));
95009b1c42SEd Schouten 
96009b1c42SEd Schouten   Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB
97009b1c42SEd Schouten   std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
98009b1c42SEd Schouten 
99009b1c42SEd Schouten   BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
100009b1c42SEd Schouten   std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
101dd58ef01SDimitry Andric   Instruction *TheInst = &*RI; // Got the corresponding instruction!
102009b1c42SEd Schouten 
103009b1c42SEd Schouten   // If this instruction produces a value, replace any users with null values
10466e41e3cSRoman Divacky   if (!TheInst->getType()->isVoidTy())
105009b1c42SEd Schouten     TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
106009b1c42SEd Schouten 
107009b1c42SEd Schouten   // Remove the instruction from the program.
108e3b55780SDimitry Andric   TheInst->eraseFromParent();
109009b1c42SEd Schouten 
110009b1c42SEd Schouten   // Spiff up the output a little bit.
111d39c594dSDimitry Andric   std::vector<std::string> Passes;
112009b1c42SEd Schouten 
113d39c594dSDimitry Andric   /// Can we get rid of the -disable-* options?
114009b1c42SEd Schouten   if (Simplification > 1 && !NoDCE)
115d39c594dSDimitry Andric     Passes.push_back("dce");
116009b1c42SEd Schouten   if (Simplification && !DisableSimplifyCFG)
117d39c594dSDimitry Andric     Passes.push_back("simplifycfg"); // Delete dead control flow
118009b1c42SEd Schouten 
119d39c594dSDimitry Andric   Passes.push_back("verify");
120eb11fae6SDimitry Andric   std::unique_ptr<Module> New = runPassesOn(Clone.get(), Passes);
121d39c594dSDimitry Andric   if (!New) {
122d39c594dSDimitry Andric     errs() << "Instruction removal failed.  Sorry. :(  Please report a bug!\n";
123d39c594dSDimitry Andric     exit(1);
124009b1c42SEd Schouten   }
125d39c594dSDimitry Andric   return New;
126009b1c42SEd Schouten }
127009b1c42SEd Schouten 
12867c32a98SDimitry Andric std::unique_ptr<Module>
performFinalCleanups(std::unique_ptr<Module> M,bool MayModifySemantics)129eb11fae6SDimitry Andric BugDriver::performFinalCleanups(std::unique_ptr<Module> M,
130eb11fae6SDimitry Andric                                 bool MayModifySemantics) {
131009b1c42SEd Schouten   // Make all functions external, so GlobalDCE doesn't delete them...
132009b1c42SEd Schouten   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
133009b1c42SEd Schouten     I->setLinkage(GlobalValue::ExternalLinkage);
134009b1c42SEd Schouten 
135d39c594dSDimitry Andric   std::vector<std::string> CleanupPasses;
136009b1c42SEd Schouten 
137009b1c42SEd Schouten   if (MayModifySemantics)
138d39c594dSDimitry Andric     CleanupPasses.push_back("deadarghaX0r");
139009b1c42SEd Schouten   else
140d39c594dSDimitry Andric     CleanupPasses.push_back("deadargelim");
141009b1c42SEd Schouten 
142eb11fae6SDimitry Andric   std::unique_ptr<Module> New = runPassesOn(M.get(), CleanupPasses);
1435ca98fd9SDimitry Andric   if (!New) {
14459850d08SRoman Divacky     errs() << "Final cleanups failed.  Sorry. :(  Please report a bug!\n";
14567c32a98SDimitry Andric     return nullptr;
146009b1c42SEd Schouten   }
147009b1c42SEd Schouten   return New;
148009b1c42SEd Schouten }
149009b1c42SEd Schouten 
extractLoop(Module * M)15067c32a98SDimitry Andric std::unique_ptr<Module> BugDriver::extractLoop(Module *M) {
151d39c594dSDimitry Andric   std::vector<std::string> LoopExtractPasses;
152d39c594dSDimitry Andric   LoopExtractPasses.push_back("loop-extract-single");
153009b1c42SEd Schouten 
15467c32a98SDimitry Andric   std::unique_ptr<Module> NewM = runPassesOn(M, LoopExtractPasses);
1555ca98fd9SDimitry Andric   if (!NewM) {
15659850d08SRoman Divacky     outs() << "*** Loop extraction failed: ";
157eb11fae6SDimitry Andric     EmitProgressBitcode(*M, "loopextraction", true);
15859850d08SRoman Divacky     outs() << "*** Sorry. :(  Please report a bug!\n";
1595ca98fd9SDimitry Andric     return nullptr;
160009b1c42SEd Schouten   }
161009b1c42SEd Schouten 
162009b1c42SEd Schouten   // Check to see if we created any new functions.  If not, no loops were
163009b1c42SEd Schouten   // extracted and we should return null.  Limit the number of loops we extract
164009b1c42SEd Schouten   // to avoid taking forever.
165009b1c42SEd Schouten   static unsigned NumExtracted = 32;
166009b1c42SEd Schouten   if (M->size() == NewM->size() || --NumExtracted == 0) {
1675ca98fd9SDimitry Andric     return nullptr;
168009b1c42SEd Schouten   } else {
169009b1c42SEd Schouten     assert(M->size() < NewM->size() && "Loop extract removed functions?");
170009b1c42SEd Schouten     Module::iterator MI = NewM->begin();
171009b1c42SEd Schouten     for (unsigned i = 0, e = M->size(); i != e; ++i)
172009b1c42SEd Schouten       ++MI;
173009b1c42SEd Schouten   }
174009b1c42SEd Schouten 
175009b1c42SEd Schouten   return NewM;
176009b1c42SEd Schouten }
177009b1c42SEd Schouten 
eliminateAliases(GlobalValue * GV)178dd58ef01SDimitry Andric static void eliminateAliases(GlobalValue *GV) {
179dd58ef01SDimitry Andric   // First, check whether a GlobalAlias references this definition.
180dd58ef01SDimitry Andric   // GlobalAlias MAY NOT reference declarations.
181dd58ef01SDimitry Andric   for (;;) {
182dd58ef01SDimitry Andric     // 1. Find aliases
183dd58ef01SDimitry Andric     SmallVector<GlobalAlias *, 1> aliases;
184dd58ef01SDimitry Andric     Module *M = GV->getParent();
185b915e9e0SDimitry Andric     for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end();
186b915e9e0SDimitry Andric          I != E; ++I)
187dd58ef01SDimitry Andric       if (I->getAliasee()->stripPointerCasts() == GV)
188dd58ef01SDimitry Andric         aliases.push_back(&*I);
189dd58ef01SDimitry Andric     if (aliases.empty())
190dd58ef01SDimitry Andric       break;
191dd58ef01SDimitry Andric     // 2. Resolve aliases
192dd58ef01SDimitry Andric     for (unsigned i = 0, e = aliases.size(); i < e; ++i) {
193dd58ef01SDimitry Andric       aliases[i]->replaceAllUsesWith(aliases[i]->getAliasee());
194dd58ef01SDimitry Andric       aliases[i]->eraseFromParent();
195dd58ef01SDimitry Andric     }
196dd58ef01SDimitry Andric     // 3. Repeat until no more aliases found; there might
197dd58ef01SDimitry Andric     // be an alias to an alias...
198dd58ef01SDimitry Andric   }
199dd58ef01SDimitry Andric }
200dd58ef01SDimitry Andric 
201dd58ef01SDimitry Andric //
202b915e9e0SDimitry Andric // DeleteGlobalInitializer - "Remove" the global variable by deleting its
203b915e9e0SDimitry Andric // initializer,
204dd58ef01SDimitry Andric // making it external.
205dd58ef01SDimitry Andric //
DeleteGlobalInitializer(GlobalVariable * GV)206dd58ef01SDimitry Andric void llvm::DeleteGlobalInitializer(GlobalVariable *GV) {
207dd58ef01SDimitry Andric   eliminateAliases(GV);
208dd58ef01SDimitry Andric   GV->setInitializer(nullptr);
20971d5a254SDimitry Andric   GV->setComdat(nullptr);
210dd58ef01SDimitry Andric }
211009b1c42SEd Schouten 
212009b1c42SEd Schouten // DeleteFunctionBody - "Remove" the function by deleting all of its basic
213009b1c42SEd Schouten // blocks, making it external.
214009b1c42SEd Schouten //
DeleteFunctionBody(Function * F)215009b1c42SEd Schouten void llvm::DeleteFunctionBody(Function *F) {
216dd58ef01SDimitry Andric   eliminateAliases(F);
21701095a5dSDimitry Andric   // Function declarations can't have comdats.
21801095a5dSDimitry Andric   F->setComdat(nullptr);
219dd58ef01SDimitry Andric 
220009b1c42SEd Schouten   // delete the body of the function...
221009b1c42SEd Schouten   F->deleteBody();
222009b1c42SEd Schouten   assert(F->isDeclaration() && "This didn't make the function external!");
223009b1c42SEd Schouten }
224009b1c42SEd Schouten 
225009b1c42SEd Schouten /// GetTorInit - Given a list of entries for static ctors/dtors, return them
226009b1c42SEd Schouten /// as a constant array.
GetTorInit(std::vector<std::pair<Function *,int>> & TorList)227009b1c42SEd Schouten static Constant *GetTorInit(std::vector<std::pair<Function *, int>> &TorList) {
228009b1c42SEd Schouten   assert(!TorList.empty() && "Don't create empty tor list!");
229009b1c42SEd Schouten   std::vector<Constant *> ArrayElts;
230411bd29eSDimitry Andric   Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext());
231411bd29eSDimitry Andric 
2326b3f41edSDimitry Andric   StructType *STy = StructType::get(Int32Ty, TorList[0].first->getType());
233009b1c42SEd Schouten   for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
234b915e9e0SDimitry Andric     Constant *Elts[] = {ConstantInt::get(Int32Ty, TorList[i].second),
235b915e9e0SDimitry Andric                         TorList[i].first};
236411bd29eSDimitry Andric     ArrayElts.push_back(ConstantStruct::get(STy, Elts));
237009b1c42SEd Schouten   }
238b915e9e0SDimitry Andric   return ConstantArray::get(
239b915e9e0SDimitry Andric       ArrayType::get(ArrayElts[0]->getType(), ArrayElts.size()), ArrayElts);
240009b1c42SEd Schouten }
241009b1c42SEd Schouten 
242009b1c42SEd Schouten /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
243009b1c42SEd Schouten /// M1 has all of the global variables.  If M2 contains any functions that are
244009b1c42SEd Schouten /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
245009b1c42SEd Schouten /// prune appropriate entries out of M1s list.
SplitStaticCtorDtor(const char * GlobalName,Module * M1,Module * M2,ValueToValueMapTy & VMap)246009b1c42SEd Schouten static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
247cf099d11SDimitry Andric                                 ValueToValueMapTy &VMap) {
248009b1c42SEd Schouten   GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
249b915e9e0SDimitry Andric   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() || !GV->use_empty())
250b915e9e0SDimitry Andric     return;
251009b1c42SEd Schouten 
252009b1c42SEd Schouten   std::vector<std::pair<Function *, int>> M1Tors, M2Tors;
253009b1c42SEd Schouten   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
254b915e9e0SDimitry Andric   if (!InitList)
255b915e9e0SDimitry Andric     return;
256009b1c42SEd Schouten 
257009b1c42SEd Schouten   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
258b915e9e0SDimitry Andric     if (ConstantStruct *CS =
259b915e9e0SDimitry Andric             dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
260b915e9e0SDimitry Andric       if (CS->getNumOperands() != 2)
261b915e9e0SDimitry Andric         return; // Not array of 2-element structs.
262009b1c42SEd Schouten 
263009b1c42SEd Schouten       if (CS->getOperand(1)->isNullValue())
264009b1c42SEd Schouten         break; // Found a null terminator, stop here.
265009b1c42SEd Schouten 
266009b1c42SEd Schouten       ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
267009b1c42SEd Schouten       int Priority = CI ? CI->getSExtValue() : 0;
268009b1c42SEd Schouten 
269009b1c42SEd Schouten       Constant *FP = CS->getOperand(1);
270009b1c42SEd Schouten       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
271009b1c42SEd Schouten         if (CE->isCast())
272009b1c42SEd Schouten           FP = CE->getOperand(0);
273009b1c42SEd Schouten       if (Function *F = dyn_cast<Function>(FP)) {
274009b1c42SEd Schouten         if (!F->isDeclaration())
275009b1c42SEd Schouten           M1Tors.push_back(std::make_pair(F, Priority));
276009b1c42SEd Schouten         else {
277009b1c42SEd Schouten           // Map to M2's version of the function.
27866e41e3cSRoman Divacky           F = cast<Function>(VMap[F]);
279009b1c42SEd Schouten           M2Tors.push_back(std::make_pair(F, Priority));
280009b1c42SEd Schouten         }
281009b1c42SEd Schouten       }
282009b1c42SEd Schouten     }
283009b1c42SEd Schouten   }
284009b1c42SEd Schouten 
285009b1c42SEd Schouten   GV->eraseFromParent();
286009b1c42SEd Schouten   if (!M1Tors.empty()) {
287009b1c42SEd Schouten     Constant *M1Init = GetTorInit(M1Tors);
28859850d08SRoman Divacky     new GlobalVariable(*M1, M1Init->getType(), false,
289b915e9e0SDimitry Andric                        GlobalValue::AppendingLinkage, M1Init, GlobalName);
290009b1c42SEd Schouten   }
291009b1c42SEd Schouten 
292009b1c42SEd Schouten   GV = M2->getNamedGlobal(GlobalName);
293009b1c42SEd Schouten   assert(GV && "Not a clone of M1?");
294009b1c42SEd Schouten   assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
295009b1c42SEd Schouten 
296009b1c42SEd Schouten   GV->eraseFromParent();
297009b1c42SEd Schouten   if (!M2Tors.empty()) {
298009b1c42SEd Schouten     Constant *M2Init = GetTorInit(M2Tors);
29959850d08SRoman Divacky     new GlobalVariable(*M2, M2Init->getType(), false,
300b915e9e0SDimitry Andric                        GlobalValue::AppendingLinkage, M2Init, GlobalName);
301009b1c42SEd Schouten   }
302009b1c42SEd Schouten }
303009b1c42SEd Schouten 
304dd58ef01SDimitry Andric std::unique_ptr<Module>
SplitFunctionsOutOfModule(Module * M,const std::vector<Function * > & F,ValueToValueMapTy & VMap)305dd58ef01SDimitry Andric llvm::SplitFunctionsOutOfModule(Module *M, const std::vector<Function *> &F,
306cf099d11SDimitry Andric                                 ValueToValueMapTy &VMap) {
307009b1c42SEd Schouten   // Make sure functions & globals are all external so that linkage
308009b1c42SEd Schouten   // between the two modules will work.
309009b1c42SEd Schouten   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
310009b1c42SEd Schouten     I->setLinkage(GlobalValue::ExternalLinkage);
311009b1c42SEd Schouten   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
312009b1c42SEd Schouten        I != E; ++I) {
31359850d08SRoman Divacky     if (I->hasName() && I->getName()[0] == '\01')
31459850d08SRoman Divacky       I->setName(I->getName().substr(1));
315009b1c42SEd Schouten     I->setLinkage(GlobalValue::ExternalLinkage);
316009b1c42SEd Schouten   }
317009b1c42SEd Schouten 
318cf099d11SDimitry Andric   ValueToValueMapTy NewVMap;
319eb11fae6SDimitry Andric   std::unique_ptr<Module> New = CloneModule(*M, NewVMap);
320009b1c42SEd Schouten 
321009b1c42SEd Schouten   // Remove the Test functions from the Safe module
322009b1c42SEd Schouten   std::set<Function *> TestFunctions;
323009b1c42SEd Schouten   for (unsigned i = 0, e = F.size(); i != e; ++i) {
32466e41e3cSRoman Divacky     Function *TNOF = cast<Function>(VMap[F[i]]);
325eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "Removing function ");
326eb11fae6SDimitry Andric     LLVM_DEBUG(TNOF->printAsOperand(errs(), false));
327eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "\n");
32866e41e3cSRoman Divacky     TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
329009b1c42SEd Schouten     DeleteFunctionBody(TNOF); // Function is now external in this module!
330009b1c42SEd Schouten   }
331009b1c42SEd Schouten 
332009b1c42SEd Schouten   // Remove the Safe functions from the Test module
333dd58ef01SDimitry Andric   for (Function &I : *New)
334dd58ef01SDimitry Andric     if (!TestFunctions.count(&I))
335dd58ef01SDimitry Andric       DeleteFunctionBody(&I);
336009b1c42SEd Schouten 
33763faed5bSDimitry Andric   // Try to split the global initializers evenly
338dd58ef01SDimitry Andric   for (GlobalVariable &I : M->globals()) {
339dd58ef01SDimitry Andric     GlobalVariable *GV = cast<GlobalVariable>(NewVMap[&I]);
340dd58ef01SDimitry Andric     if (Function *TestFn = globalInitUsesExternalBA(&I)) {
34163faed5bSDimitry Andric       if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
34263faed5bSDimitry Andric         errs() << "*** Error: when reducing functions, encountered "
34363faed5bSDimitry Andric                   "the global '";
3445ca98fd9SDimitry Andric         GV->printAsOperand(errs(), false);
34563faed5bSDimitry Andric         errs() << "' with an initializer that references blockaddresses "
346b915e9e0SDimitry Andric                   "from safe function '"
347b915e9e0SDimitry Andric                << SafeFn->getName() << "' and from test function '"
348b915e9e0SDimitry Andric                << TestFn->getName() << "'.\n";
34963faed5bSDimitry Andric         exit(1);
35063faed5bSDimitry Andric       }
351dd58ef01SDimitry Andric       DeleteGlobalInitializer(&I); // Delete the initializer to make it external
35263faed5bSDimitry Andric     } else {
35363faed5bSDimitry Andric       // If we keep it in the safe module, then delete it in the test module
354dd58ef01SDimitry Andric       DeleteGlobalInitializer(GV);
35563faed5bSDimitry Andric     }
35663faed5bSDimitry Andric   }
35763faed5bSDimitry Andric 
358009b1c42SEd Schouten   // Make sure that there is a global ctor/dtor array in both halves of the
359009b1c42SEd Schouten   // module if they both have static ctor/dtor functions.
360dd58ef01SDimitry Andric   SplitStaticCtorDtor("llvm.global_ctors", M, New.get(), NewVMap);
361dd58ef01SDimitry Andric   SplitStaticCtorDtor("llvm.global_dtors", M, New.get(), NewVMap);
362009b1c42SEd Schouten 
363009b1c42SEd Schouten   return New;
364009b1c42SEd Schouten }
365009b1c42SEd Schouten 
366009b1c42SEd Schouten //===----------------------------------------------------------------------===//
367009b1c42SEd Schouten // Basic Block Extraction Code
368009b1c42SEd Schouten //===----------------------------------------------------------------------===//
369009b1c42SEd Schouten 
37067c32a98SDimitry Andric std::unique_ptr<Module>
extractMappedBlocksFromModule(const std::vector<BasicBlock * > & BBs,Module * M)37167c32a98SDimitry Andric BugDriver::extractMappedBlocksFromModule(const std::vector<BasicBlock *> &BBs,
372009b1c42SEd Schouten                                          Module *M) {
373044eb2f6SDimitry Andric   auto Temp = sys::fs::TempFile::create(OutputPrefix + "-extractblocks%%%%%%%");
374044eb2f6SDimitry Andric   if (!Temp) {
37559850d08SRoman Divacky     outs() << "*** Basic Block extraction failed!\n";
376044eb2f6SDimitry Andric     errs() << "Error creating temporary file: " << toString(Temp.takeError())
377044eb2f6SDimitry Andric            << "\n";
378eb11fae6SDimitry Andric     EmitProgressBitcode(*M, "basicblockextractfail", true);
3795ca98fd9SDimitry Andric     return nullptr;
380009b1c42SEd Schouten   }
381044eb2f6SDimitry Andric   DiscardTemp Discard{*Temp};
382009b1c42SEd Schouten 
383eb11fae6SDimitry Andric   // Extract all of the blocks except the ones in BBs.
384eb11fae6SDimitry Andric   SmallVector<BasicBlock *, 32> BlocksToExtract;
385eb11fae6SDimitry Andric   for (Function &F : *M)
386eb11fae6SDimitry Andric     for (BasicBlock &BB : F)
387eb11fae6SDimitry Andric       // Check if this block is going to be extracted.
388b60736ecSDimitry Andric       if (!llvm::is_contained(BBs, &BB))
389eb11fae6SDimitry Andric         BlocksToExtract.push_back(&BB);
390eb11fae6SDimitry Andric 
391044eb2f6SDimitry Andric   raw_fd_ostream OS(Temp->FD, /*shouldClose*/ false);
392eb11fae6SDimitry Andric   for (BasicBlock *BB : BBs) {
393009b1c42SEd Schouten     // If the BB doesn't have a name, give it one so we have something to key
394009b1c42SEd Schouten     // off of.
395b915e9e0SDimitry Andric     if (!BB->hasName())
396b915e9e0SDimitry Andric       BB->setName("tmpbb");
397044eb2f6SDimitry Andric     OS << BB->getParent()->getName() << " " << BB->getName() << "\n";
398009b1c42SEd Schouten   }
399044eb2f6SDimitry Andric   OS.flush();
400044eb2f6SDimitry Andric   if (OS.has_error()) {
401f8af5cf6SDimitry Andric     errs() << "Error writing list of blocks to not extract\n";
402eb11fae6SDimitry Andric     EmitProgressBitcode(*M, "basicblockextractfail", true);
403044eb2f6SDimitry Andric     OS.clear_error();
4045ca98fd9SDimitry Andric     return nullptr;
405d39c594dSDimitry Andric   }
406009b1c42SEd Schouten 
407f8af5cf6SDimitry Andric   std::string uniqueFN = "--extract-blocks-file=";
408044eb2f6SDimitry Andric   uniqueFN += Temp->TmpName;
409009b1c42SEd Schouten 
410d39c594dSDimitry Andric   std::vector<std::string> PI;
411d39c594dSDimitry Andric   PI.push_back("extract-blocks");
4121d5ae102SDimitry Andric   std::unique_ptr<Module> Ret = runPassesOn(M, PI, {uniqueFN});
413009b1c42SEd Schouten 
4145ca98fd9SDimitry Andric   if (!Ret) {
41559850d08SRoman Divacky     outs() << "*** Basic Block extraction failed, please report a bug!\n";
416eb11fae6SDimitry Andric     EmitProgressBitcode(*M, "basicblockextractfail", true);
417009b1c42SEd Schouten   }
418009b1c42SEd Schouten   return Ret;
419009b1c42SEd Schouten }
420