ReduceGlobalVars.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //===- ReduceGlobalVars.cpp - Specialized Delta Pass ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a function which calls the Generic Delta pass in order
  10. // to reduce Global Variables in the provided Module.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ReduceGlobalVars.h"
  14. #include "llvm/IR/Constants.h"
  15. #include <set>
  16. using namespace llvm;
  17. /// Removes all the GVs that aren't inside the desired Chunks.
  18. static void extractGVsFromModule(Oracle &O, Module &Program) {
  19. // Get GVs inside desired chunks
  20. std::vector<GlobalVariable *> InitGVsToKeep;
  21. for (auto &GV : Program.globals())
  22. if (O.shouldKeep())
  23. InitGVsToKeep.push_back(&GV);
  24. // We create a vector first, then convert it to a set, so that we don't have
  25. // to pay the cost of rebalancing the set frequently if the order we insert
  26. // the elements doesn't match the order they should appear inside the set.
  27. std::set<GlobalVariable *> GVsToKeep(InitGVsToKeep.begin(),
  28. InitGVsToKeep.end());
  29. // Delete out-of-chunk GVs and their uses
  30. std::vector<GlobalVariable *> ToRemove;
  31. std::vector<WeakVH> InstToRemove;
  32. for (auto &GV : Program.globals())
  33. if (!GVsToKeep.count(&GV)) {
  34. for (auto *U : GV.users())
  35. if (auto *Inst = dyn_cast<Instruction>(U))
  36. InstToRemove.push_back(Inst);
  37. GV.replaceAllUsesWith(UndefValue::get(GV.getType()));
  38. ToRemove.push_back(&GV);
  39. }
  40. // Delete (unique) Instruction uses of unwanted GVs
  41. for (Value *V : InstToRemove) {
  42. if (!V)
  43. continue;
  44. auto *Inst = cast<Instruction>(V);
  45. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  46. Inst->eraseFromParent();
  47. }
  48. for (auto *GV : ToRemove)
  49. GV->eraseFromParent();
  50. }
  51. void llvm::reduceGlobalsDeltaPass(TestRunner &Test) {
  52. outs() << "*** Reducing GVs...\n";
  53. runDeltaPass(Test, extractGVsFromModule);
  54. }