ConstantMerge.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
  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 defines the interface to a pass that merges duplicate global
  11. // constants together into a single constant that is shared. This is useful
  12. // because some passes (ie TraceValues) insert a lot of string constants into
  13. // the program, regardless of whether or not an existing string is available.
  14. //
  15. // Algorithm: ConstantMerge is designed to build up a map of available constants
  16. // and eliminate duplicates when it is initialized.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "llvm/Transforms/IPO.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/PointerIntPair.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/Pass.h"
  30. using namespace llvm;
  31. #define DEBUG_TYPE "constmerge"
  32. STATISTIC(NumMerged, "Number of global constants merged");
  33. namespace {
  34. struct ConstantMerge : public ModulePass {
  35. static char ID; // Pass identification, replacement for typeid
  36. ConstantMerge() : ModulePass(ID) {
  37. initializeConstantMergePass(*PassRegistry::getPassRegistry());
  38. }
  39. // For this pass, process all of the globals in the module, eliminating
  40. // duplicate constants.
  41. bool runOnModule(Module &M) override;
  42. // Return true iff we can determine the alignment of this global variable.
  43. bool hasKnownAlignment(GlobalVariable *GV) const;
  44. // Return the alignment of the global, including converting the default
  45. // alignment to a concrete value.
  46. unsigned getAlignment(GlobalVariable *GV) const;
  47. };
  48. }
  49. char ConstantMerge::ID = 0;
  50. INITIALIZE_PASS(ConstantMerge, "constmerge",
  51. "Merge Duplicate Global Constants", false, false)
  52. ModulePass *llvm::createConstantMergePass() { return new ConstantMerge(); }
  53. /// Find values that are marked as llvm.used.
  54. static void FindUsedValues(GlobalVariable *LLVMUsed,
  55. SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
  56. if (!LLVMUsed) return;
  57. ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
  58. for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
  59. Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
  60. GlobalValue *GV = cast<GlobalValue>(Operand);
  61. UsedValues.insert(GV);
  62. }
  63. }
  64. // True if A is better than B.
  65. static bool IsBetterCanonical(const GlobalVariable &A,
  66. const GlobalVariable &B) {
  67. if (!A.hasLocalLinkage() && B.hasLocalLinkage())
  68. return true;
  69. if (A.hasLocalLinkage() && !B.hasLocalLinkage())
  70. return false;
  71. return A.hasUnnamedAddr();
  72. }
  73. unsigned ConstantMerge::getAlignment(GlobalVariable *GV) const {
  74. unsigned Align = GV->getAlignment();
  75. if (Align)
  76. return Align;
  77. return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
  78. }
  79. bool ConstantMerge::runOnModule(Module &M) {
  80. // Find all the globals that are marked "used". These cannot be merged.
  81. SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
  82. FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
  83. FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
  84. // Map unique constants to globals.
  85. DenseMap<Constant *, GlobalVariable *> CMap;
  86. // Replacements - This vector contains a list of replacements to perform.
  87. SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
  88. bool MadeChange = false;
  89. // Iterate constant merging while we are still making progress. Merging two
  90. // constants together may allow us to merge other constants together if the
  91. // second level constants have initializers which point to the globals that
  92. // were just merged.
  93. while (1) {
  94. // First: Find the canonical constants others will be merged with.
  95. for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
  96. GVI != E; ) {
  97. GlobalVariable *GV = GVI++;
  98. // If this GV is dead, remove it.
  99. GV->removeDeadConstantUsers();
  100. if (GV->use_empty() && GV->hasLocalLinkage()) {
  101. GV->eraseFromParent();
  102. continue;
  103. }
  104. // Only process constants with initializers in the default address space.
  105. if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
  106. GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
  107. // Don't touch values marked with attribute(used).
  108. UsedGlobals.count(GV))
  109. continue;
  110. // This transformation is legal for weak ODR globals in the sense it
  111. // doesn't change semantics, but we really don't want to perform it
  112. // anyway; it's likely to pessimize code generation, and some tools
  113. // (like the Darwin linker in cases involving CFString) don't expect it.
  114. if (GV->isWeakForLinker())
  115. continue;
  116. Constant *Init = GV->getInitializer();
  117. // Check to see if the initializer is already known.
  118. GlobalVariable *&Slot = CMap[Init];
  119. // If this is the first constant we find or if the old one is local,
  120. // replace with the current one. If the current is externally visible
  121. // it cannot be replace, but can be the canonical constant we merge with.
  122. if (!Slot || IsBetterCanonical(*GV, *Slot))
  123. Slot = GV;
  124. }
  125. // Second: identify all globals that can be merged together, filling in
  126. // the Replacements vector. We cannot do the replacement in this pass
  127. // because doing so may cause initializers of other globals to be rewritten,
  128. // invalidating the Constant* pointers in CMap.
  129. for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
  130. GVI != E; ) {
  131. GlobalVariable *GV = GVI++;
  132. // Only process constants with initializers in the default address space.
  133. if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
  134. GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
  135. // Don't touch values marked with attribute(used).
  136. UsedGlobals.count(GV))
  137. continue;
  138. // We can only replace constant with local linkage.
  139. if (!GV->hasLocalLinkage())
  140. continue;
  141. Constant *Init = GV->getInitializer();
  142. // Check to see if the initializer is already known.
  143. GlobalVariable *Slot = CMap[Init];
  144. if (!Slot || Slot == GV)
  145. continue;
  146. if (!Slot->hasUnnamedAddr() && !GV->hasUnnamedAddr())
  147. continue;
  148. if (!GV->hasUnnamedAddr())
  149. Slot->setUnnamedAddr(false);
  150. // Make all uses of the duplicate constant use the canonical version.
  151. Replacements.push_back(std::make_pair(GV, Slot));
  152. }
  153. if (Replacements.empty())
  154. return MadeChange;
  155. CMap.clear();
  156. // Now that we have figured out which replacements must be made, do them all
  157. // now. This avoid invalidating the pointers in CMap, which are unneeded
  158. // now.
  159. for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
  160. // Bump the alignment if necessary.
  161. if (Replacements[i].first->getAlignment() ||
  162. Replacements[i].second->getAlignment()) {
  163. Replacements[i].second->setAlignment(
  164. std::max(getAlignment(Replacements[i].first),
  165. getAlignment(Replacements[i].second)));
  166. }
  167. // Eliminate any uses of the dead global.
  168. Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
  169. // Delete the global value from the module.
  170. assert(Replacements[i].first->hasLocalLinkage() &&
  171. "Refusing to delete an externally visible global variable.");
  172. Replacements[i].first->eraseFromParent();
  173. }
  174. NumMerged += Replacements.size();
  175. Replacements.clear();
  176. }
  177. }