GlobalMerge.cpp 25 KB

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