GlobalMerge.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //===-- GlobalMerge.cpp - Internal globals merging -----------------------===//
  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. // This pass merges globals with internal linkage into one. This way all the
  10. // globals which were merged into a biggest one can be addressed using offsets
  11. // from the same base pointer (no need for separate base pointer for each of the
  12. // global). Such a transformation can significantly reduce the register pressure
  13. // when many globals are involved.
  14. //
  15. // For example, consider the code which touches several global variables at
  16. // once:
  17. //
  18. // static int foo[N], bar[N], baz[N];
  19. //
  20. // for (i = 0; i < N; ++i) {
  21. // foo[i] = bar[i] * baz[i];
  22. // }
  23. //
  24. // On ARM the addresses of 3 arrays should be kept in the registers, thus
  25. // this code has quite large register pressure (loop body):
  26. //
  27. // ldr r1, [r5], #4
  28. // ldr r2, [r6], #4
  29. // mul r1, r2, r1
  30. // str r1, [r0], #4
  31. //
  32. // Pass converts the code to something like:
  33. //
  34. // static struct {
  35. // int foo[N];
  36. // int bar[N];
  37. // int baz[N];
  38. // } merged;
  39. //
  40. // for (i = 0; i < N; ++i) {
  41. // merged.foo[i] = merged.bar[i] * merged.baz[i];
  42. // }
  43. //
  44. // and in ARM code this becomes:
  45. //
  46. // ldr r0, [r5, #40]
  47. // ldr r1, [r5, #80]
  48. // mul r0, r1, r0
  49. // str r0, [r5], #4
  50. //
  51. // note that we saved 2 registers here almostly "for free".
  52. // ===---------------------------------------------------------------------===//
  53. #include "llvm/Transforms/Scalar.h"
  54. #include "llvm/ADT/SmallPtrSet.h"
  55. #include "llvm/ADT/Statistic.h"
  56. #include "llvm/CodeGen/Passes.h"
  57. #include "llvm/IR/Attributes.h"
  58. #include "llvm/IR/Constants.h"
  59. #include "llvm/IR/DataLayout.h"
  60. #include "llvm/IR/DerivedTypes.h"
  61. #include "llvm/IR/Function.h"
  62. #include "llvm/IR/GlobalVariable.h"
  63. #include "llvm/IR/Instructions.h"
  64. #include "llvm/IR/Intrinsics.h"
  65. #include "llvm/IR/Module.h"
  66. #include "llvm/Pass.h"
  67. #include "llvm/Support/CommandLine.h"
  68. #include "llvm/Target/TargetLowering.h"
  69. #include "llvm/Target/TargetLoweringObjectFile.h"
  70. #include "llvm/Target/TargetSubtargetInfo.h"
  71. using namespace llvm;
  72. #define DEBUG_TYPE "global-merge"
  73. static cl::opt<bool>
  74. EnableGlobalMerge("enable-global-merge", cl::Hidden,
  75. cl::desc("Enable global merge pass"),
  76. cl::init(true));
  77. static cl::opt<bool>
  78. EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
  79. cl::desc("Enable global merge pass on constants"),
  80. cl::init(false));
  81. // FIXME: this could be a transitional option, and we probably need to remove
  82. // it if only we are sure this optimization could always benefit all targets.
  83. static cl::opt<bool>
  84. EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
  85. cl::desc("Enable global merge pass on external linkage"),
  86. cl::init(false));
  87. STATISTIC(NumMerged , "Number of globals merged");
  88. namespace {
  89. class GlobalMerge : public FunctionPass {
  90. const TargetMachine *TM;
  91. bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
  92. Module &M, bool isConst, unsigned AddrSpace) const;
  93. /// \brief Check if the given variable has been identified as must keep
  94. /// \pre setMustKeepGlobalVariables must have been called on the Module that
  95. /// contains GV
  96. bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
  97. return MustKeepGlobalVariables.count(GV);
  98. }
  99. /// Collect every variables marked as "used" or used in a landing pad
  100. /// instruction for this Module.
  101. void setMustKeepGlobalVariables(Module &M);
  102. /// Collect every variables marked as "used"
  103. void collectUsedGlobalVariables(Module &M);
  104. /// Keep track of the GlobalVariable that must not be merged away
  105. SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
  106. public:
  107. static char ID; // Pass identification, replacement for typeid.
  108. explicit GlobalMerge(const TargetMachine *TM = nullptr)
  109. : FunctionPass(ID), TM(TM) {
  110. initializeGlobalMergePass(*PassRegistry::getPassRegistry());
  111. }
  112. bool doInitialization(Module &M) override;
  113. bool runOnFunction(Function &F) override;
  114. bool doFinalization(Module &M) override;
  115. const char *getPassName() const override {
  116. return "Merge internal globals";
  117. }
  118. void getAnalysisUsage(AnalysisUsage &AU) const override {
  119. AU.setPreservesCFG();
  120. FunctionPass::getAnalysisUsage(AU);
  121. }
  122. };
  123. } // end anonymous namespace
  124. char GlobalMerge::ID = 0;
  125. INITIALIZE_TM_PASS(GlobalMerge, "global-merge", "Merge global variables",
  126. false, false)
  127. bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
  128. Module &M, bool isConst, unsigned AddrSpace) const {
  129. const TargetLowering *TLI = TM->getSubtargetImpl()->getTargetLowering();
  130. const DataLayout *DL = TLI->getDataLayout();
  131. // FIXME: Infer the maximum possible offset depending on the actual users
  132. // (these max offsets are different for the users inside Thumb or ARM
  133. // functions)
  134. unsigned MaxOffset = TLI->getMaximalGlobalOffset();
  135. // FIXME: Find better heuristics
  136. std::stable_sort(Globals.begin(), Globals.end(),
  137. [DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
  138. Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
  139. Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
  140. return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
  141. });
  142. Type *Int32Ty = Type::getInt32Ty(M.getContext());
  143. assert(Globals.size() > 1);
  144. // FIXME: This simple solution merges globals all together as maximum as
  145. // possible. However, with this solution it would be hard to remove dead
  146. // global symbols at link-time. An alternative solution could be checking
  147. // global symbols references function by function, and make the symbols
  148. // being referred in the same function merged and we would probably need
  149. // to introduce heuristic algorithm to solve the merge conflict from
  150. // different functions.
  151. for (size_t i = 0, e = Globals.size(); i != e; ) {
  152. size_t j = 0;
  153. uint64_t MergedSize = 0;
  154. std::vector<Type*> Tys;
  155. std::vector<Constant*> Inits;
  156. bool HasExternal = false;
  157. GlobalVariable *TheFirstExternal = 0;
  158. for (j = i; j != e; ++j) {
  159. Type *Ty = Globals[j]->getType()->getElementType();
  160. MergedSize += DL->getTypeAllocSize(Ty);
  161. if (MergedSize > MaxOffset) {
  162. break;
  163. }
  164. Tys.push_back(Ty);
  165. Inits.push_back(Globals[j]->getInitializer());
  166. if (Globals[j]->hasExternalLinkage() && !HasExternal) {
  167. HasExternal = true;
  168. TheFirstExternal = Globals[j];
  169. }
  170. }
  171. // If merged variables doesn't have external linkage, we needn't to expose
  172. // the symbol after merging.
  173. GlobalValue::LinkageTypes Linkage = HasExternal
  174. ? GlobalValue::ExternalLinkage
  175. : GlobalValue::InternalLinkage;
  176. StructType *MergedTy = StructType::get(M.getContext(), Tys);
  177. Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
  178. // If merged variables have external linkage, we use symbol name of the
  179. // first variable merged as the suffix of global symbol name. This would
  180. // be able to avoid the link-time naming conflict for globalm symbols.
  181. GlobalVariable *MergedGV = new GlobalVariable(
  182. M, MergedTy, isConst, Linkage, MergedInit,
  183. HasExternal ? "_MergedGlobals_" + TheFirstExternal->getName()
  184. : "_MergedGlobals",
  185. nullptr, GlobalVariable::NotThreadLocal, AddrSpace);
  186. for (size_t k = i; k < j; ++k) {
  187. GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
  188. std::string Name = Globals[k]->getName();
  189. Constant *Idx[2] = {
  190. ConstantInt::get(Int32Ty, 0),
  191. ConstantInt::get(Int32Ty, k-i)
  192. };
  193. Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx);
  194. Globals[k]->replaceAllUsesWith(GEP);
  195. Globals[k]->eraseFromParent();
  196. if (Linkage != GlobalValue::InternalLinkage) {
  197. // Generate a new alias...
  198. auto *PTy = cast<PointerType>(GEP->getType());
  199. GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
  200. Linkage, Name, GEP, &M);
  201. }
  202. NumMerged++;
  203. }
  204. i = j;
  205. }
  206. return true;
  207. }
  208. void GlobalMerge::collectUsedGlobalVariables(Module &M) {
  209. // Extract global variables from llvm.used array
  210. const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
  211. if (!GV || !GV->hasInitializer()) return;
  212. // Should be an array of 'i8*'.
  213. const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
  214. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  215. if (const GlobalVariable *G =
  216. dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
  217. MustKeepGlobalVariables.insert(G);
  218. }
  219. void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
  220. collectUsedGlobalVariables(M);
  221. for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
  222. ++IFn) {
  223. for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
  224. IBB != IEndBB; ++IBB) {
  225. // Follow the invoke link to find the landing pad instruction
  226. const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
  227. if (!II) continue;
  228. const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
  229. // Look for globals in the clauses of the landing pad instruction
  230. for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
  231. Idx != NumClauses; ++Idx)
  232. if (const GlobalVariable *GV =
  233. dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
  234. ->stripPointerCasts()))
  235. MustKeepGlobalVariables.insert(GV);
  236. }
  237. }
  238. }
  239. bool GlobalMerge::doInitialization(Module &M) {
  240. if (!EnableGlobalMerge)
  241. return false;
  242. DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
  243. BSSGlobals;
  244. const TargetLowering *TLI = TM->getSubtargetImpl()->getTargetLowering();
  245. const DataLayout *DL = TLI->getDataLayout();
  246. unsigned MaxOffset = TLI->getMaximalGlobalOffset();
  247. bool Changed = false;
  248. setMustKeepGlobalVariables(M);
  249. // Grab all non-const globals.
  250. for (Module::global_iterator I = M.global_begin(),
  251. E = M.global_end(); I != E; ++I) {
  252. // Merge is safe for "normal" internal or external globals only
  253. if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
  254. continue;
  255. if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
  256. !I->hasInternalLinkage())
  257. continue;
  258. PointerType *PT = dyn_cast<PointerType>(I->getType());
  259. assert(PT && "Global variable is not a pointer!");
  260. unsigned AddressSpace = PT->getAddressSpace();
  261. // Ignore fancy-aligned globals for now.
  262. unsigned Alignment = DL->getPreferredAlignment(I);
  263. Type *Ty = I->getType()->getElementType();
  264. if (Alignment > DL->getABITypeAlignment(Ty))
  265. continue;
  266. // Ignore all 'special' globals.
  267. if (I->getName().startswith("llvm.") ||
  268. I->getName().startswith(".llvm."))
  269. continue;
  270. // Ignore all "required" globals:
  271. if (isMustKeepGlobalVariable(I))
  272. continue;
  273. if (DL->getTypeAllocSize(Ty) < MaxOffset) {
  274. if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
  275. BSSGlobals[AddressSpace].push_back(I);
  276. else if (I->isConstant())
  277. ConstGlobals[AddressSpace].push_back(I);
  278. else
  279. Globals[AddressSpace].push_back(I);
  280. }
  281. }
  282. for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
  283. I = Globals.begin(), E = Globals.end(); I != E; ++I)
  284. if (I->second.size() > 1)
  285. Changed |= doMerge(I->second, M, false, I->first);
  286. for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
  287. I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
  288. if (I->second.size() > 1)
  289. Changed |= doMerge(I->second, M, false, I->first);
  290. if (EnableGlobalMergeOnConst)
  291. for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
  292. I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
  293. if (I->second.size() > 1)
  294. Changed |= doMerge(I->second, M, true, I->first);
  295. return Changed;
  296. }
  297. bool GlobalMerge::runOnFunction(Function &F) {
  298. return false;
  299. }
  300. bool GlobalMerge::doFinalization(Module &M) {
  301. MustKeepGlobalVariables.clear();
  302. return false;
  303. }
  304. Pass *llvm::createGlobalMergePass(const TargetMachine *TM) {
  305. return new GlobalMerge(TM);
  306. }