GlobalMerge.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. //===- GlobalMerge.cpp - Internal globals merging -------------------------===//
  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 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. // However, merging globals can have tradeoffs:
  54. // - it confuses debuggers, tools, and users
  55. // - it makes linker optimizations less useful (order files, LOHs, ...)
  56. // - it forces usage of indexed addressing (which isn't necessarily "free")
  57. // - it can increase register pressure when the uses are disparate enough.
  58. //
  59. // We use heuristics to discover the best global grouping we can (cf cl::opts).
  60. //
  61. // ===---------------------------------------------------------------------===//
  62. #include "llvm/ADT/BitVector.h"
  63. #include "llvm/ADT/DenseMap.h"
  64. #include "llvm/ADT/SmallPtrSet.h"
  65. #include "llvm/ADT/SmallVector.h"
  66. #include "llvm/ADT/Statistic.h"
  67. #include "llvm/ADT/StringRef.h"
  68. #include "llvm/ADT/Triple.h"
  69. #include "llvm/ADT/Twine.h"
  70. #include "llvm/CodeGen/Passes.h"
  71. #include "llvm/IR/BasicBlock.h"
  72. #include "llvm/IR/Constants.h"
  73. #include "llvm/IR/DataLayout.h"
  74. #include "llvm/IR/DerivedTypes.h"
  75. #include "llvm/IR/Function.h"
  76. #include "llvm/IR/GlobalAlias.h"
  77. #include "llvm/IR/GlobalValue.h"
  78. #include "llvm/IR/GlobalVariable.h"
  79. #include "llvm/IR/Instruction.h"
  80. #include "llvm/IR/Module.h"
  81. #include "llvm/IR/Type.h"
  82. #include "llvm/IR/Use.h"
  83. #include "llvm/IR/User.h"
  84. #include "llvm/Pass.h"
  85. #include "llvm/Support/Casting.h"
  86. #include "llvm/Support/CommandLine.h"
  87. #include "llvm/Support/Debug.h"
  88. #include "llvm/Support/raw_ostream.h"
  89. #include "llvm/Target/TargetLoweringObjectFile.h"
  90. #include "llvm/Target/TargetMachine.h"
  91. #include <algorithm>
  92. #include <cassert>
  93. #include <cstddef>
  94. #include <cstdint>
  95. #include <string>
  96. #include <vector>
  97. using namespace llvm;
  98. #define DEBUG_TYPE "global-merge"
  99. // FIXME: This is only useful as a last-resort way to disable the pass.
  100. static cl::opt<bool>
  101. EnableGlobalMerge("enable-global-merge", cl::Hidden,
  102. cl::desc("Enable the global merge pass"),
  103. cl::init(true));
  104. static cl::opt<unsigned>
  105. GlobalMergeMaxOffset("global-merge-max-offset", cl::Hidden,
  106. cl::desc("Set maximum offset for global merge pass"),
  107. cl::init(0));
  108. static cl::opt<bool> GlobalMergeGroupByUse(
  109. "global-merge-group-by-use", cl::Hidden,
  110. cl::desc("Improve global merge pass to look at uses"), cl::init(true));
  111. static cl::opt<bool> GlobalMergeIgnoreSingleUse(
  112. "global-merge-ignore-single-use", cl::Hidden,
  113. cl::desc("Improve global merge pass to ignore globals only used alone"),
  114. cl::init(true));
  115. static cl::opt<bool>
  116. EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
  117. cl::desc("Enable global merge pass on constants"),
  118. cl::init(false));
  119. // FIXME: this could be a transitional option, and we probably need to remove
  120. // it if only we are sure this optimization could always benefit all targets.
  121. static cl::opt<cl::boolOrDefault>
  122. EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
  123. cl::desc("Enable global merge pass on external linkage"));
  124. STATISTIC(NumMerged, "Number of globals merged");
  125. namespace {
  126. class GlobalMerge : public FunctionPass {
  127. const TargetMachine *TM = nullptr;
  128. // FIXME: Infer the maximum possible offset depending on the actual users
  129. // (these max offsets are different for the users inside Thumb or ARM
  130. // functions), see the code that passes in the offset in the ARM backend
  131. // for more information.
  132. unsigned MaxOffset;
  133. /// Whether we should try to optimize for size only.
  134. /// Currently, this applies a dead simple heuristic: only consider globals
  135. /// used in minsize functions for merging.
  136. /// FIXME: This could learn about optsize, and be used in the cost model.
  137. bool OnlyOptimizeForSize = false;
  138. /// Whether we should merge global variables that have external linkage.
  139. bool MergeExternalGlobals = false;
  140. bool IsMachO;
  141. bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
  142. Module &M, bool isConst, unsigned AddrSpace) const;
  143. /// Merge everything in \p Globals for which the corresponding bit
  144. /// in \p GlobalSet is set.
  145. bool doMerge(const SmallVectorImpl<GlobalVariable *> &Globals,
  146. const BitVector &GlobalSet, Module &M, bool isConst,
  147. unsigned AddrSpace) const;
  148. /// Check if the given variable has been identified as must keep
  149. /// \pre setMustKeepGlobalVariables must have been called on the Module that
  150. /// contains GV
  151. bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
  152. return MustKeepGlobalVariables.count(GV);
  153. }
  154. /// Collect every variables marked as "used" or used in a landing pad
  155. /// instruction for this Module.
  156. void setMustKeepGlobalVariables(Module &M);
  157. /// Collect every variables marked as "used"
  158. void collectUsedGlobalVariables(Module &M, StringRef Name);
  159. /// Keep track of the GlobalVariable that must not be merged away
  160. SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
  161. public:
  162. static char ID; // Pass identification, replacement for typeid.
  163. explicit GlobalMerge()
  164. : FunctionPass(ID), MaxOffset(GlobalMergeMaxOffset) {
  165. initializeGlobalMergePass(*PassRegistry::getPassRegistry());
  166. }
  167. explicit GlobalMerge(const TargetMachine *TM, unsigned MaximalOffset,
  168. bool OnlyOptimizeForSize, bool MergeExternalGlobals)
  169. : FunctionPass(ID), TM(TM), MaxOffset(MaximalOffset),
  170. OnlyOptimizeForSize(OnlyOptimizeForSize),
  171. MergeExternalGlobals(MergeExternalGlobals) {
  172. initializeGlobalMergePass(*PassRegistry::getPassRegistry());
  173. }
  174. bool doInitialization(Module &M) override;
  175. bool runOnFunction(Function &F) override;
  176. bool doFinalization(Module &M) override;
  177. StringRef getPassName() const override { return "Merge internal globals"; }
  178. void getAnalysisUsage(AnalysisUsage &AU) const override {
  179. AU.setPreservesCFG();
  180. FunctionPass::getAnalysisUsage(AU);
  181. }
  182. };
  183. } // end anonymous namespace
  184. char GlobalMerge::ID = 0;
  185. INITIALIZE_PASS(GlobalMerge, DEBUG_TYPE, "Merge global variables", false, false)
  186. bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
  187. Module &M, bool isConst, unsigned AddrSpace) const {
  188. auto &DL = M.getDataLayout();
  189. // FIXME: Find better heuristics
  190. std::stable_sort(Globals.begin(), Globals.end(),
  191. [&DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
  192. return DL.getTypeAllocSize(GV1->getValueType()) <
  193. DL.getTypeAllocSize(GV2->getValueType());
  194. });
  195. // If we want to just blindly group all globals together, do so.
  196. if (!GlobalMergeGroupByUse) {
  197. BitVector AllGlobals(Globals.size());
  198. AllGlobals.set();
  199. return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
  200. }
  201. // If we want to be smarter, look at all uses of each global, to try to
  202. // discover all sets of globals used together, and how many times each of
  203. // these sets occurred.
  204. //
  205. // Keep this reasonably efficient, by having an append-only list of all sets
  206. // discovered so far (UsedGlobalSet), and mapping each "together-ness" unit of
  207. // code (currently, a Function) to the set of globals seen so far that are
  208. // used together in that unit (GlobalUsesByFunction).
  209. //
  210. // When we look at the Nth global, we know that any new set is either:
  211. // - the singleton set {N}, containing this global only, or
  212. // - the union of {N} and a previously-discovered set, containing some
  213. // combination of the previous N-1 globals.
  214. // Using that knowledge, when looking at the Nth global, we can keep:
  215. // - a reference to the singleton set {N} (CurGVOnlySetIdx)
  216. // - a list mapping each previous set to its union with {N} (EncounteredUGS),
  217. // if it actually occurs.
  218. // We keep track of the sets of globals used together "close enough".
  219. struct UsedGlobalSet {
  220. BitVector Globals;
  221. unsigned UsageCount = 1;
  222. UsedGlobalSet(size_t Size) : Globals(Size) {}
  223. };
  224. // Each set is unique in UsedGlobalSets.
  225. std::vector<UsedGlobalSet> UsedGlobalSets;
  226. // Avoid repeating the create-global-set pattern.
  227. auto CreateGlobalSet = [&]() -> UsedGlobalSet & {
  228. UsedGlobalSets.emplace_back(Globals.size());
  229. return UsedGlobalSets.back();
  230. };
  231. // The first set is the empty set.
  232. CreateGlobalSet().UsageCount = 0;
  233. // We define "close enough" to be "in the same function".
  234. // FIXME: Grouping uses by function is way too aggressive, so we should have
  235. // a better metric for distance between uses.
  236. // The obvious alternative would be to group by BasicBlock, but that's in
  237. // turn too conservative..
  238. // Anything in between wouldn't be trivial to compute, so just stick with
  239. // per-function grouping.
  240. // The value type is an index into UsedGlobalSets.
  241. // The default (0) conveniently points to the empty set.
  242. DenseMap<Function *, size_t /*UsedGlobalSetIdx*/> GlobalUsesByFunction;
  243. // Now, look at each merge-eligible global in turn.
  244. // Keep track of the sets we already encountered to which we added the
  245. // current global.
  246. // Each element matches the same-index element in UsedGlobalSets.
  247. // This lets us efficiently tell whether a set has already been expanded to
  248. // include the current global.
  249. std::vector<size_t> EncounteredUGS;
  250. for (size_t GI = 0, GE = Globals.size(); GI != GE; ++GI) {
  251. GlobalVariable *GV = Globals[GI];
  252. // Reset the encountered sets for this global...
  253. std::fill(EncounteredUGS.begin(), EncounteredUGS.end(), 0);
  254. // ...and grow it in case we created new sets for the previous global.
  255. EncounteredUGS.resize(UsedGlobalSets.size());
  256. // We might need to create a set that only consists of the current global.
  257. // Keep track of its index into UsedGlobalSets.
  258. size_t CurGVOnlySetIdx = 0;
  259. // For each global, look at all its Uses.
  260. for (auto &U : GV->uses()) {
  261. // This Use might be a ConstantExpr. We're interested in Instruction
  262. // users, so look through ConstantExpr...
  263. Use *UI, *UE;
  264. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
  265. if (CE->use_empty())
  266. continue;
  267. UI = &*CE->use_begin();
  268. UE = nullptr;
  269. } else if (isa<Instruction>(U.getUser())) {
  270. UI = &U;
  271. UE = UI->getNext();
  272. } else {
  273. continue;
  274. }
  275. // ...to iterate on all the instruction users of the global.
  276. // Note that we iterate on Uses and not on Users to be able to getNext().
  277. for (; UI != UE; UI = UI->getNext()) {
  278. Instruction *I = dyn_cast<Instruction>(UI->getUser());
  279. if (!I)
  280. continue;
  281. Function *ParentFn = I->getParent()->getParent();
  282. // If we're only optimizing for size, ignore non-minsize functions.
  283. if (OnlyOptimizeForSize && !ParentFn->hasMinSize())
  284. continue;
  285. size_t UGSIdx = GlobalUsesByFunction[ParentFn];
  286. // If this is the first global the basic block uses, map it to the set
  287. // consisting of this global only.
  288. if (!UGSIdx) {
  289. // If that set doesn't exist yet, create it.
  290. if (!CurGVOnlySetIdx) {
  291. CurGVOnlySetIdx = UsedGlobalSets.size();
  292. CreateGlobalSet().Globals.set(GI);
  293. } else {
  294. ++UsedGlobalSets[CurGVOnlySetIdx].UsageCount;
  295. }
  296. GlobalUsesByFunction[ParentFn] = CurGVOnlySetIdx;
  297. continue;
  298. }
  299. // If we already encountered this BB, just increment the counter.
  300. if (UsedGlobalSets[UGSIdx].Globals.test(GI)) {
  301. ++UsedGlobalSets[UGSIdx].UsageCount;
  302. continue;
  303. }
  304. // If not, the previous set wasn't actually used in this function.
  305. --UsedGlobalSets[UGSIdx].UsageCount;
  306. // If we already expanded the previous set to include this global, just
  307. // reuse that expanded set.
  308. if (size_t ExpandedIdx = EncounteredUGS[UGSIdx]) {
  309. ++UsedGlobalSets[ExpandedIdx].UsageCount;
  310. GlobalUsesByFunction[ParentFn] = ExpandedIdx;
  311. continue;
  312. }
  313. // If not, create a new set consisting of the union of the previous set
  314. // and this global. Mark it as encountered, so we can reuse it later.
  315. GlobalUsesByFunction[ParentFn] = EncounteredUGS[UGSIdx] =
  316. UsedGlobalSets.size();
  317. UsedGlobalSet &NewUGS = CreateGlobalSet();
  318. NewUGS.Globals.set(GI);
  319. NewUGS.Globals |= UsedGlobalSets[UGSIdx].Globals;
  320. }
  321. }
  322. }
  323. // Now we found a bunch of sets of globals used together. We accumulated
  324. // the number of times we encountered the sets (i.e., the number of blocks
  325. // that use that exact set of globals).
  326. //
  327. // Multiply that by the size of the set to give us a crude profitability
  328. // metric.
  329. std::stable_sort(UsedGlobalSets.begin(), UsedGlobalSets.end(),
  330. [](const UsedGlobalSet &UGS1, const UsedGlobalSet &UGS2) {
  331. return UGS1.Globals.count() * UGS1.UsageCount <
  332. UGS2.Globals.count() * UGS2.UsageCount;
  333. });
  334. // We can choose to merge all globals together, but ignore globals never used
  335. // with another global. This catches the obviously non-profitable cases of
  336. // having a single global, but is aggressive enough for any other case.
  337. if (GlobalMergeIgnoreSingleUse) {
  338. BitVector AllGlobals(Globals.size());
  339. for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
  340. const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
  341. if (UGS.UsageCount == 0)
  342. continue;
  343. if (UGS.Globals.count() > 1)
  344. AllGlobals |= UGS.Globals;
  345. }
  346. return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
  347. }
  348. // Starting from the sets with the best (=biggest) profitability, find a
  349. // good combination.
  350. // The ideal (and expensive) solution can only be found by trying all
  351. // combinations, looking for the one with the best profitability.
  352. // Don't be smart about it, and just pick the first compatible combination,
  353. // starting with the sets with the best profitability.
  354. BitVector PickedGlobals(Globals.size());
  355. bool Changed = false;
  356. for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
  357. const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
  358. if (UGS.UsageCount == 0)
  359. continue;
  360. if (PickedGlobals.anyCommon(UGS.Globals))
  361. continue;
  362. PickedGlobals |= UGS.Globals;
  363. // If the set only contains one global, there's no point in merging.
  364. // Ignore the global for inclusion in other sets though, so keep it in
  365. // PickedGlobals.
  366. if (UGS.Globals.count() < 2)
  367. continue;
  368. Changed |= doMerge(Globals, UGS.Globals, M, isConst, AddrSpace);
  369. }
  370. return Changed;
  371. }
  372. bool GlobalMerge::doMerge(const SmallVectorImpl<GlobalVariable *> &Globals,
  373. const BitVector &GlobalSet, Module &M, bool isConst,
  374. unsigned AddrSpace) const {
  375. assert(Globals.size() > 1);
  376. Type *Int32Ty = Type::getInt32Ty(M.getContext());
  377. Type *Int8Ty = Type::getInt8Ty(M.getContext());
  378. auto &DL = M.getDataLayout();
  379. LLVM_DEBUG(dbgs() << " Trying to merge set, starts with #"
  380. << GlobalSet.find_first() << "\n");
  381. bool Changed = false;
  382. ssize_t i = GlobalSet.find_first();
  383. while (i != -1) {
  384. ssize_t j = 0;
  385. uint64_t MergedSize = 0;
  386. std::vector<Type*> Tys;
  387. std::vector<Constant*> Inits;
  388. std::vector<unsigned> StructIdxs;
  389. bool HasExternal = false;
  390. StringRef FirstExternalName;
  391. unsigned MaxAlign = 1;
  392. unsigned CurIdx = 0;
  393. for (j = i; j != -1; j = GlobalSet.find_next(j)) {
  394. Type *Ty = Globals[j]->getValueType();
  395. // Make sure we use the same alignment AsmPrinter would use.
  396. unsigned Align = DL.getPreferredAlignment(Globals[j]);
  397. unsigned Padding = alignTo(MergedSize, Align) - MergedSize;
  398. MergedSize += Padding;
  399. MergedSize += DL.getTypeAllocSize(Ty);
  400. if (MergedSize > MaxOffset) {
  401. break;
  402. }
  403. if (Padding) {
  404. Tys.push_back(ArrayType::get(Int8Ty, Padding));
  405. Inits.push_back(ConstantAggregateZero::get(Tys.back()));
  406. ++CurIdx;
  407. }
  408. Tys.push_back(Ty);
  409. Inits.push_back(Globals[j]->getInitializer());
  410. StructIdxs.push_back(CurIdx++);
  411. MaxAlign = std::max(MaxAlign, Align);
  412. if (Globals[j]->hasExternalLinkage() && !HasExternal) {
  413. HasExternal = true;
  414. FirstExternalName = Globals[j]->getName();
  415. }
  416. }
  417. // Exit early if there is only one global to merge.
  418. if (Tys.size() < 2) {
  419. i = j;
  420. continue;
  421. }
  422. // If merged variables doesn't have external linkage, we needn't to expose
  423. // the symbol after merging.
  424. GlobalValue::LinkageTypes Linkage = HasExternal
  425. ? GlobalValue::ExternalLinkage
  426. : GlobalValue::InternalLinkage;
  427. // Use a packed struct so we can control alignment.
  428. StructType *MergedTy = StructType::get(M.getContext(), Tys, true);
  429. Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
  430. // On Darwin external linkage needs to be preserved, otherwise
  431. // dsymutil cannot preserve the debug info for the merged
  432. // variables. If they have external linkage, use the symbol name
  433. // of the first variable merged as the suffix of global symbol
  434. // name. This avoids a link-time naming conflict for the
  435. // _MergedGlobals symbols.
  436. Twine MergedName =
  437. (IsMachO && HasExternal)
  438. ? "_MergedGlobals_" + FirstExternalName
  439. : "_MergedGlobals";
  440. auto MergedLinkage = IsMachO ? Linkage : GlobalValue::PrivateLinkage;
  441. auto *MergedGV = new GlobalVariable(
  442. M, MergedTy, isConst, MergedLinkage, MergedInit, MergedName, nullptr,
  443. GlobalVariable::NotThreadLocal, AddrSpace);
  444. MergedGV->setAlignment(MaxAlign);
  445. MergedGV->setSection(Globals[i]->getSection());
  446. const StructLayout *MergedLayout = DL.getStructLayout(MergedTy);
  447. for (ssize_t k = i, idx = 0; k != j; k = GlobalSet.find_next(k), ++idx) {
  448. GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
  449. std::string Name = Globals[k]->getName();
  450. GlobalValue::DLLStorageClassTypes DLLStorage =
  451. Globals[k]->getDLLStorageClass();
  452. // Copy metadata while adjusting any debug info metadata by the original
  453. // global's offset within the merged global.
  454. MergedGV->copyMetadata(Globals[k],
  455. MergedLayout->getElementOffset(StructIdxs[idx]));
  456. Constant *Idx[2] = {
  457. ConstantInt::get(Int32Ty, 0),
  458. ConstantInt::get(Int32Ty, StructIdxs[idx]),
  459. };
  460. Constant *GEP =
  461. ConstantExpr::getInBoundsGetElementPtr(MergedTy, MergedGV, Idx);
  462. Globals[k]->replaceAllUsesWith(GEP);
  463. Globals[k]->eraseFromParent();
  464. // When the linkage is not internal we must emit an alias for the original
  465. // variable name as it may be accessed from another object. On non-Mach-O
  466. // we can also emit an alias for internal linkage as it's safe to do so.
  467. // It's not safe on Mach-O as the alias (and thus the portion of the
  468. // MergedGlobals variable) may be dead stripped at link time.
  469. if (Linkage != GlobalValue::InternalLinkage || !IsMachO) {
  470. GlobalAlias *GA = GlobalAlias::create(Tys[StructIdxs[idx]], AddrSpace,
  471. Linkage, Name, GEP, &M);
  472. GA->setDLLStorageClass(DLLStorage);
  473. }
  474. NumMerged++;
  475. }
  476. Changed = true;
  477. i = j;
  478. }
  479. return Changed;
  480. }
  481. void GlobalMerge::collectUsedGlobalVariables(Module &M, StringRef Name) {
  482. // Extract global variables from llvm.used array
  483. const GlobalVariable *GV = M.getGlobalVariable(Name);
  484. if (!GV || !GV->hasInitializer()) return;
  485. // Should be an array of 'i8*'.
  486. const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
  487. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  488. if (const GlobalVariable *G =
  489. dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
  490. MustKeepGlobalVariables.insert(G);
  491. }
  492. void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
  493. collectUsedGlobalVariables(M, "llvm.used");
  494. collectUsedGlobalVariables(M, "llvm.compiler.used");
  495. for (Function &F : M) {
  496. for (BasicBlock &BB : F) {
  497. Instruction *Pad = BB.getFirstNonPHI();
  498. if (!Pad->isEHPad())
  499. continue;
  500. // Keep globals used by landingpads and catchpads.
  501. for (const Use &U : Pad->operands()) {
  502. if (const GlobalVariable *GV =
  503. dyn_cast<GlobalVariable>(U->stripPointerCasts()))
  504. MustKeepGlobalVariables.insert(GV);
  505. }
  506. }
  507. }
  508. }
  509. bool GlobalMerge::doInitialization(Module &M) {
  510. if (!EnableGlobalMerge)
  511. return false;
  512. IsMachO = Triple(M.getTargetTriple()).isOSBinFormatMachO();
  513. auto &DL = M.getDataLayout();
  514. DenseMap<std::pair<unsigned, StringRef>, SmallVector<GlobalVariable *, 16>>
  515. Globals, ConstGlobals, BSSGlobals;
  516. bool Changed = false;
  517. setMustKeepGlobalVariables(M);
  518. // Grab all non-const globals.
  519. for (auto &GV : M.globals()) {
  520. // Merge is safe for "normal" internal or external globals only
  521. if (GV.isDeclaration() || GV.isThreadLocal() || GV.hasImplicitSection())
  522. continue;
  523. // It's not safe to merge globals that may be preempted
  524. if (TM && !TM->shouldAssumeDSOLocal(M, &GV))
  525. continue;
  526. if (!(MergeExternalGlobals && GV.hasExternalLinkage()) &&
  527. !GV.hasInternalLinkage())
  528. continue;
  529. PointerType *PT = dyn_cast<PointerType>(GV.getType());
  530. assert(PT && "Global variable is not a pointer!");
  531. unsigned AddressSpace = PT->getAddressSpace();
  532. StringRef Section = GV.getSection();
  533. // Ignore all 'special' globals.
  534. if (GV.getName().startswith("llvm.") ||
  535. GV.getName().startswith(".llvm."))
  536. continue;
  537. // Ignore all "required" globals:
  538. if (isMustKeepGlobalVariable(&GV))
  539. continue;
  540. Type *Ty = GV.getValueType();
  541. if (DL.getTypeAllocSize(Ty) < MaxOffset) {
  542. if (TM &&
  543. TargetLoweringObjectFile::getKindForGlobal(&GV, *TM).isBSS())
  544. BSSGlobals[{AddressSpace, Section}].push_back(&GV);
  545. else if (GV.isConstant())
  546. ConstGlobals[{AddressSpace, Section}].push_back(&GV);
  547. else
  548. Globals[{AddressSpace, Section}].push_back(&GV);
  549. }
  550. }
  551. for (auto &P : Globals)
  552. if (P.second.size() > 1)
  553. Changed |= doMerge(P.second, M, false, P.first.first);
  554. for (auto &P : BSSGlobals)
  555. if (P.second.size() > 1)
  556. Changed |= doMerge(P.second, M, false, P.first.first);
  557. if (EnableGlobalMergeOnConst)
  558. for (auto &P : ConstGlobals)
  559. if (P.second.size() > 1)
  560. Changed |= doMerge(P.second, M, true, P.first.first);
  561. return Changed;
  562. }
  563. bool GlobalMerge::runOnFunction(Function &F) {
  564. return false;
  565. }
  566. bool GlobalMerge::doFinalization(Module &M) {
  567. MustKeepGlobalVariables.clear();
  568. return false;
  569. }
  570. Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset,
  571. bool OnlyOptimizeForSize,
  572. bool MergeExternalByDefault) {
  573. bool MergeExternal = (EnableGlobalMergeOnExternal == cl::BOU_UNSET) ?
  574. MergeExternalByDefault : (EnableGlobalMergeOnExternal == cl::BOU_TRUE);
  575. return new GlobalMerge(TM, Offset, OnlyOptimizeForSize, MergeExternal);
  576. }