ReduceGlobalVars.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 "Utils.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/Transforms/Utils/ModuleUtils.h"
  17. using namespace llvm;
  18. static bool shouldAlwaysKeep(const GlobalVariable &GV) {
  19. return GV.getName() == "llvm.used" || GV.getName() == "llvm.compiler.used";
  20. }
  21. /// Removes all the GVs that aren't inside the desired Chunks.
  22. static void extractGVsFromModule(Oracle &O, ReducerWorkItem &WorkItem) {
  23. Module &Program = WorkItem.getModule();
  24. // Get GVs inside desired chunks
  25. std::vector<Constant *> InitGVsToKeep;
  26. for (auto &GV : Program.globals()) {
  27. if (shouldAlwaysKeep(GV) || O.shouldKeep())
  28. InitGVsToKeep.push_back(&GV);
  29. }
  30. // We create a vector first, then convert it to a set, so that we don't have
  31. // to pay the cost of rebalancing the set frequently if the order we insert
  32. // the elements doesn't match the order they should appear inside the set.
  33. DenseSet<Constant *> GVsToKeep(InitGVsToKeep.begin(), InitGVsToKeep.end());
  34. // Delete out-of-chunk GVs and their uses
  35. DenseSet<Constant *> ToRemove;
  36. for (auto &GV : Program.globals()) {
  37. if (!GVsToKeep.count(&GV))
  38. ToRemove.insert(&GV);
  39. }
  40. removeFromUsedLists(Program,
  41. [&ToRemove](Constant *C) { return ToRemove.count(C); });
  42. for (auto *GV : ToRemove) {
  43. GV->replaceAllUsesWith(getDefaultValue(GV->getType()));
  44. cast<GlobalVariable>(GV)->eraseFromParent();
  45. }
  46. }
  47. void llvm::reduceGlobalsDeltaPass(TestRunner &Test) {
  48. runDeltaPass(Test, extractGVsFromModule, "Reducing GlobalVariables");
  49. }