LTO.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  1. //===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
  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 functions and classes used to support LTO.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/LTO/LTO.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  15. #include "llvm/Analysis/StackSafetyAnalysis.h"
  16. #include "llvm/Analysis/TargetLibraryInfo.h"
  17. #include "llvm/Analysis/TargetTransformInfo.h"
  18. #include "llvm/Bitcode/BitcodeReader.h"
  19. #include "llvm/Bitcode/BitcodeWriter.h"
  20. #include "llvm/CodeGen/Analysis.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/IR/AutoUpgrade.h"
  23. #include "llvm/IR/DiagnosticPrinter.h"
  24. #include "llvm/IR/Intrinsics.h"
  25. #include "llvm/IR/LLVMRemarkStreamer.h"
  26. #include "llvm/IR/LegacyPassManager.h"
  27. #include "llvm/IR/Mangler.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/LTO/LTOBackend.h"
  30. #include "llvm/LTO/SummaryBasedOptimizations.h"
  31. #include "llvm/Linker/IRMover.h"
  32. #include "llvm/Object/IRObjectFile.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Error.h"
  35. #include "llvm/Support/ManagedStatic.h"
  36. #include "llvm/Support/MemoryBuffer.h"
  37. #include "llvm/Support/Path.h"
  38. #include "llvm/Support/SHA1.h"
  39. #include "llvm/Support/SourceMgr.h"
  40. #include "llvm/Support/TargetRegistry.h"
  41. #include "llvm/Support/ThreadPool.h"
  42. #include "llvm/Support/Threading.h"
  43. #include "llvm/Support/TimeProfiler.h"
  44. #include "llvm/Support/VCSRevision.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include "llvm/Target/TargetMachine.h"
  47. #include "llvm/Target/TargetOptions.h"
  48. #include "llvm/Transforms/IPO.h"
  49. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  50. #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
  51. #include "llvm/Transforms/Utils/FunctionImportUtils.h"
  52. #include "llvm/Transforms/Utils/SplitModule.h"
  53. #include <set>
  54. using namespace llvm;
  55. using namespace lto;
  56. using namespace object;
  57. #define DEBUG_TYPE "lto"
  58. static cl::opt<bool>
  59. DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
  60. cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
  61. /// Enable global value internalization in LTO.
  62. cl::opt<bool> EnableLTOInternalization(
  63. "enable-lto-internalization", cl::init(true), cl::Hidden,
  64. cl::desc("Enable global value internalization in LTO"));
  65. // Computes a unique hash for the Module considering the current list of
  66. // export/import and other global analysis results.
  67. // The hash is produced in \p Key.
  68. void llvm::computeLTOCacheKey(
  69. SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
  70. StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
  71. const FunctionImporter::ExportSetTy &ExportList,
  72. const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
  73. const GVSummaryMapTy &DefinedGlobals,
  74. const std::set<GlobalValue::GUID> &CfiFunctionDefs,
  75. const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
  76. // Compute the unique hash for this entry.
  77. // This is based on the current compiler version, the module itself, the
  78. // export list, the hash for every single module in the import list, the
  79. // list of ResolvedODR for the module, and the list of preserved symbols.
  80. SHA1 Hasher;
  81. // Start with the compiler revision
  82. Hasher.update(LLVM_VERSION_STRING);
  83. #ifdef LLVM_REVISION
  84. Hasher.update(LLVM_REVISION);
  85. #endif
  86. // Include the parts of the LTO configuration that affect code generation.
  87. auto AddString = [&](StringRef Str) {
  88. Hasher.update(Str);
  89. Hasher.update(ArrayRef<uint8_t>{0});
  90. };
  91. auto AddUnsigned = [&](unsigned I) {
  92. uint8_t Data[4];
  93. support::endian::write32le(Data, I);
  94. Hasher.update(ArrayRef<uint8_t>{Data, 4});
  95. };
  96. auto AddUint64 = [&](uint64_t I) {
  97. uint8_t Data[8];
  98. support::endian::write64le(Data, I);
  99. Hasher.update(ArrayRef<uint8_t>{Data, 8});
  100. };
  101. AddString(Conf.CPU);
  102. // FIXME: Hash more of Options. For now all clients initialize Options from
  103. // command-line flags (which is unsupported in production), but may set
  104. // RelaxELFRelocations. The clang driver can also pass FunctionSections,
  105. // DataSections and DebuggerTuning via command line flags.
  106. AddUnsigned(Conf.Options.RelaxELFRelocations);
  107. AddUnsigned(Conf.Options.FunctionSections);
  108. AddUnsigned(Conf.Options.DataSections);
  109. AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
  110. for (auto &A : Conf.MAttrs)
  111. AddString(A);
  112. if (Conf.RelocModel)
  113. AddUnsigned(*Conf.RelocModel);
  114. else
  115. AddUnsigned(-1);
  116. if (Conf.CodeModel)
  117. AddUnsigned(*Conf.CodeModel);
  118. else
  119. AddUnsigned(-1);
  120. AddUnsigned(Conf.CGOptLevel);
  121. AddUnsigned(Conf.CGFileType);
  122. AddUnsigned(Conf.OptLevel);
  123. AddUnsigned(Conf.UseNewPM);
  124. AddUnsigned(Conf.Freestanding);
  125. AddString(Conf.OptPipeline);
  126. AddString(Conf.AAPipeline);
  127. AddString(Conf.OverrideTriple);
  128. AddString(Conf.DefaultTriple);
  129. AddString(Conf.DwoDir);
  130. // Include the hash for the current module
  131. auto ModHash = Index.getModuleHash(ModuleID);
  132. Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
  133. std::vector<uint64_t> ExportsGUID;
  134. ExportsGUID.reserve(ExportList.size());
  135. for (const auto &VI : ExportList) {
  136. auto GUID = VI.getGUID();
  137. ExportsGUID.push_back(GUID);
  138. }
  139. // Sort the export list elements GUIDs.
  140. llvm::sort(ExportsGUID);
  141. for (uint64_t GUID : ExportsGUID) {
  142. // The export list can impact the internalization, be conservative here
  143. Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
  144. }
  145. // Include the hash for every module we import functions from. The set of
  146. // imported symbols for each module may affect code generation and is
  147. // sensitive to link order, so include that as well.
  148. using ImportMapIteratorTy = FunctionImporter::ImportMapTy::const_iterator;
  149. std::vector<ImportMapIteratorTy> ImportModulesVector;
  150. ImportModulesVector.reserve(ImportList.size());
  151. for (ImportMapIteratorTy It = ImportList.begin(); It != ImportList.end();
  152. ++It) {
  153. ImportModulesVector.push_back(It);
  154. }
  155. llvm::sort(ImportModulesVector,
  156. [](const ImportMapIteratorTy &Lhs, const ImportMapIteratorTy &Rhs)
  157. -> bool { return Lhs->getKey() < Rhs->getKey(); });
  158. for (const ImportMapIteratorTy &EntryIt : ImportModulesVector) {
  159. auto ModHash = Index.getModuleHash(EntryIt->first());
  160. Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
  161. AddUint64(EntryIt->second.size());
  162. for (auto &Fn : EntryIt->second)
  163. AddUint64(Fn);
  164. }
  165. // Include the hash for the resolved ODR.
  166. for (auto &Entry : ResolvedODR) {
  167. Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
  168. sizeof(GlobalValue::GUID)));
  169. Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
  170. sizeof(GlobalValue::LinkageTypes)));
  171. }
  172. // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
  173. // defined in this module.
  174. std::set<GlobalValue::GUID> UsedCfiDefs;
  175. std::set<GlobalValue::GUID> UsedCfiDecls;
  176. // Typeids used in this module.
  177. std::set<GlobalValue::GUID> UsedTypeIds;
  178. auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
  179. if (CfiFunctionDefs.count(ValueGUID))
  180. UsedCfiDefs.insert(ValueGUID);
  181. if (CfiFunctionDecls.count(ValueGUID))
  182. UsedCfiDecls.insert(ValueGUID);
  183. };
  184. auto AddUsedThings = [&](GlobalValueSummary *GS) {
  185. if (!GS) return;
  186. AddUnsigned(GS->isLive());
  187. AddUnsigned(GS->canAutoHide());
  188. for (const ValueInfo &VI : GS->refs()) {
  189. AddUnsigned(VI.isDSOLocal());
  190. AddUsedCfiGlobal(VI.getGUID());
  191. }
  192. if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
  193. AddUnsigned(GVS->maybeReadOnly());
  194. AddUnsigned(GVS->maybeWriteOnly());
  195. }
  196. if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
  197. for (auto &TT : FS->type_tests())
  198. UsedTypeIds.insert(TT);
  199. for (auto &TT : FS->type_test_assume_vcalls())
  200. UsedTypeIds.insert(TT.GUID);
  201. for (auto &TT : FS->type_checked_load_vcalls())
  202. UsedTypeIds.insert(TT.GUID);
  203. for (auto &TT : FS->type_test_assume_const_vcalls())
  204. UsedTypeIds.insert(TT.VFunc.GUID);
  205. for (auto &TT : FS->type_checked_load_const_vcalls())
  206. UsedTypeIds.insert(TT.VFunc.GUID);
  207. for (auto &ET : FS->calls()) {
  208. AddUnsigned(ET.first.isDSOLocal());
  209. AddUsedCfiGlobal(ET.first.getGUID());
  210. }
  211. }
  212. };
  213. // Include the hash for the linkage type to reflect internalization and weak
  214. // resolution, and collect any used type identifier resolutions.
  215. for (auto &GS : DefinedGlobals) {
  216. GlobalValue::LinkageTypes Linkage = GS.second->linkage();
  217. Hasher.update(
  218. ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
  219. AddUsedCfiGlobal(GS.first);
  220. AddUsedThings(GS.second);
  221. }
  222. // Imported functions may introduce new uses of type identifier resolutions,
  223. // so we need to collect their used resolutions as well.
  224. for (auto &ImpM : ImportList)
  225. for (auto &ImpF : ImpM.second) {
  226. GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first());
  227. AddUsedThings(S);
  228. // If this is an alias, we also care about any types/etc. that the aliasee
  229. // may reference.
  230. if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
  231. AddUsedThings(AS->getBaseObject());
  232. }
  233. auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
  234. AddString(TId);
  235. AddUnsigned(S.TTRes.TheKind);
  236. AddUnsigned(S.TTRes.SizeM1BitWidth);
  237. AddUint64(S.TTRes.AlignLog2);
  238. AddUint64(S.TTRes.SizeM1);
  239. AddUint64(S.TTRes.BitMask);
  240. AddUint64(S.TTRes.InlineBits);
  241. AddUint64(S.WPDRes.size());
  242. for (auto &WPD : S.WPDRes) {
  243. AddUnsigned(WPD.first);
  244. AddUnsigned(WPD.second.TheKind);
  245. AddString(WPD.second.SingleImplName);
  246. AddUint64(WPD.second.ResByArg.size());
  247. for (auto &ByArg : WPD.second.ResByArg) {
  248. AddUint64(ByArg.first.size());
  249. for (uint64_t Arg : ByArg.first)
  250. AddUint64(Arg);
  251. AddUnsigned(ByArg.second.TheKind);
  252. AddUint64(ByArg.second.Info);
  253. AddUnsigned(ByArg.second.Byte);
  254. AddUnsigned(ByArg.second.Bit);
  255. }
  256. }
  257. };
  258. // Include the hash for all type identifiers used by this module.
  259. for (GlobalValue::GUID TId : UsedTypeIds) {
  260. auto TidIter = Index.typeIds().equal_range(TId);
  261. for (auto It = TidIter.first; It != TidIter.second; ++It)
  262. AddTypeIdSummary(It->second.first, It->second.second);
  263. }
  264. AddUnsigned(UsedCfiDefs.size());
  265. for (auto &V : UsedCfiDefs)
  266. AddUint64(V);
  267. AddUnsigned(UsedCfiDecls.size());
  268. for (auto &V : UsedCfiDecls)
  269. AddUint64(V);
  270. if (!Conf.SampleProfile.empty()) {
  271. auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
  272. if (FileOrErr) {
  273. Hasher.update(FileOrErr.get()->getBuffer());
  274. if (!Conf.ProfileRemapping.empty()) {
  275. FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
  276. if (FileOrErr)
  277. Hasher.update(FileOrErr.get()->getBuffer());
  278. }
  279. }
  280. }
  281. Key = toHex(Hasher.result());
  282. }
  283. static void thinLTOResolvePrevailingGUID(
  284. ValueInfo VI, DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
  285. function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
  286. isPrevailing,
  287. function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
  288. recordNewLinkage,
  289. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
  290. for (auto &S : VI.getSummaryList()) {
  291. GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
  292. // Ignore local and appending linkage values since the linker
  293. // doesn't resolve them.
  294. if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
  295. GlobalValue::isAppendingLinkage(S->linkage()))
  296. continue;
  297. // We need to emit only one of these. The prevailing module will keep it,
  298. // but turned into a weak, while the others will drop it when possible.
  299. // This is both a compile-time optimization and a correctness
  300. // transformation. This is necessary for correctness when we have exported
  301. // a reference - we need to convert the linkonce to weak to
  302. // ensure a copy is kept to satisfy the exported reference.
  303. // FIXME: We may want to split the compile time and correctness
  304. // aspects into separate routines.
  305. if (isPrevailing(VI.getGUID(), S.get())) {
  306. if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
  307. S->setLinkage(GlobalValue::getWeakLinkage(
  308. GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
  309. // The kept copy is eligible for auto-hiding (hidden visibility) if all
  310. // copies were (i.e. they were all linkonce_odr global unnamed addr).
  311. // If any copy is not (e.g. it was originally weak_odr), then the symbol
  312. // must remain externally available (e.g. a weak_odr from an explicitly
  313. // instantiated template). Additionally, if it is in the
  314. // GUIDPreservedSymbols set, that means that it is visibile outside
  315. // the summary (e.g. in a native object or a bitcode file without
  316. // summary), and in that case we cannot hide it as it isn't possible to
  317. // check all copies.
  318. S->setCanAutoHide(VI.canAutoHide() &&
  319. !GUIDPreservedSymbols.count(VI.getGUID()));
  320. }
  321. }
  322. // Alias and aliasee can't be turned into available_externally.
  323. else if (!isa<AliasSummary>(S.get()) &&
  324. !GlobalInvolvedWithAlias.count(S.get()))
  325. S->setLinkage(GlobalValue::AvailableExternallyLinkage);
  326. if (S->linkage() != OriginalLinkage)
  327. recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
  328. }
  329. }
  330. /// Resolve linkage for prevailing symbols in the \p Index.
  331. //
  332. // We'd like to drop these functions if they are no longer referenced in the
  333. // current module. However there is a chance that another module is still
  334. // referencing them because of the import. We make sure we always emit at least
  335. // one copy.
  336. void llvm::thinLTOResolvePrevailingInIndex(
  337. ModuleSummaryIndex &Index,
  338. function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
  339. isPrevailing,
  340. function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
  341. recordNewLinkage,
  342. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
  343. // We won't optimize the globals that are referenced by an alias for now
  344. // Ideally we should turn the alias into a global and duplicate the definition
  345. // when needed.
  346. DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
  347. for (auto &I : Index)
  348. for (auto &S : I.second.SummaryList)
  349. if (auto AS = dyn_cast<AliasSummary>(S.get()))
  350. GlobalInvolvedWithAlias.insert(&AS->getAliasee());
  351. for (auto &I : Index)
  352. thinLTOResolvePrevailingGUID(Index.getValueInfo(I), GlobalInvolvedWithAlias,
  353. isPrevailing, recordNewLinkage,
  354. GUIDPreservedSymbols);
  355. }
  356. static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS) {
  357. if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject()))
  358. return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
  359. (VarSummary->linkage() == GlobalValue::WeakODRLinkage ||
  360. VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage);
  361. return false;
  362. }
  363. static void thinLTOInternalizeAndPromoteGUID(
  364. ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
  365. function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
  366. isPrevailing) {
  367. for (auto &S : VI.getSummaryList()) {
  368. if (isExported(S->modulePath(), VI)) {
  369. if (GlobalValue::isLocalLinkage(S->linkage()))
  370. S->setLinkage(GlobalValue::ExternalLinkage);
  371. } else if (EnableLTOInternalization &&
  372. // Ignore local and appending linkage values since the linker
  373. // doesn't resolve them.
  374. !GlobalValue::isLocalLinkage(S->linkage()) &&
  375. (!GlobalValue::isInterposableLinkage(S->linkage()) ||
  376. isPrevailing(VI.getGUID(), S.get())) &&
  377. S->linkage() != GlobalValue::AppendingLinkage &&
  378. // We can't internalize available_externally globals because this
  379. // can break function pointer equality.
  380. S->linkage() != GlobalValue::AvailableExternallyLinkage &&
  381. // Functions and read-only variables with linkonce_odr and
  382. // weak_odr linkage can be internalized. We can't internalize
  383. // linkonce_odr and weak_odr variables which are both modified
  384. // and read somewhere in the program because reads and writes
  385. // will become inconsistent.
  386. !isWeakObjectWithRWAccess(S.get()))
  387. S->setLinkage(GlobalValue::InternalLinkage);
  388. }
  389. }
  390. // Update the linkages in the given \p Index to mark exported values
  391. // as external and non-exported values as internal.
  392. void llvm::thinLTOInternalizeAndPromoteInIndex(
  393. ModuleSummaryIndex &Index,
  394. function_ref<bool(StringRef, ValueInfo)> isExported,
  395. function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
  396. isPrevailing) {
  397. for (auto &I : Index)
  398. thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
  399. isPrevailing);
  400. }
  401. // Requires a destructor for std::vector<InputModule>.
  402. InputFile::~InputFile() = default;
  403. Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
  404. std::unique_ptr<InputFile> File(new InputFile);
  405. Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
  406. if (!FOrErr)
  407. return FOrErr.takeError();
  408. File->TargetTriple = FOrErr->TheReader.getTargetTriple();
  409. File->SourceFileName = FOrErr->TheReader.getSourceFileName();
  410. File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
  411. File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
  412. File->ComdatTable = FOrErr->TheReader.getComdatTable();
  413. for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
  414. size_t Begin = File->Symbols.size();
  415. for (const irsymtab::Reader::SymbolRef &Sym :
  416. FOrErr->TheReader.module_symbols(I))
  417. // Skip symbols that are irrelevant to LTO. Note that this condition needs
  418. // to match the one in Skip() in LTO::addRegularLTO().
  419. if (Sym.isGlobal() && !Sym.isFormatSpecific())
  420. File->Symbols.push_back(Sym);
  421. File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
  422. }
  423. File->Mods = FOrErr->Mods;
  424. File->Strtab = std::move(FOrErr->Strtab);
  425. return std::move(File);
  426. }
  427. StringRef InputFile::getName() const {
  428. return Mods[0].getModuleIdentifier();
  429. }
  430. BitcodeModule &InputFile::getSingleBitcodeModule() {
  431. assert(Mods.size() == 1 && "Expect only one bitcode module");
  432. return Mods[0];
  433. }
  434. LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
  435. const Config &Conf)
  436. : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
  437. Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
  438. Mover(std::make_unique<IRMover>(*CombinedModule)) {}
  439. LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
  440. : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
  441. if (!Backend)
  442. this->Backend =
  443. createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
  444. }
  445. LTO::LTO(Config Conf, ThinBackend Backend,
  446. unsigned ParallelCodeGenParallelismLevel)
  447. : Conf(std::move(Conf)),
  448. RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
  449. ThinLTO(std::move(Backend)) {}
  450. // Requires a destructor for MapVector<BitcodeModule>.
  451. LTO::~LTO() = default;
  452. // Add the symbols in the given module to the GlobalResolutions map, and resolve
  453. // their partitions.
  454. void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
  455. ArrayRef<SymbolResolution> Res,
  456. unsigned Partition, bool InSummary) {
  457. auto *ResI = Res.begin();
  458. auto *ResE = Res.end();
  459. (void)ResE;
  460. for (const InputFile::Symbol &Sym : Syms) {
  461. assert(ResI != ResE);
  462. SymbolResolution Res = *ResI++;
  463. StringRef Name = Sym.getName();
  464. Triple TT(RegularLTO.CombinedModule->getTargetTriple());
  465. // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
  466. // way they are handled by lld), otherwise we can end up with two
  467. // global resolutions (one with and one for a copy of the symbol without).
  468. if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
  469. Name = Name.substr(strlen("__imp_"));
  470. auto &GlobalRes = GlobalResolutions[Name];
  471. GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
  472. if (Res.Prevailing) {
  473. assert(!GlobalRes.Prevailing &&
  474. "Multiple prevailing defs are not allowed");
  475. GlobalRes.Prevailing = true;
  476. GlobalRes.IRName = std::string(Sym.getIRName());
  477. } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
  478. // Sometimes it can be two copies of symbol in a module and prevailing
  479. // symbol can have no IR name. That might happen if symbol is defined in
  480. // module level inline asm block. In case we have multiple modules with
  481. // the same symbol we want to use IR name of the prevailing symbol.
  482. // Otherwise, if we haven't seen a prevailing symbol, set the name so that
  483. // we can later use it to check if there is any prevailing copy in IR.
  484. GlobalRes.IRName = std::string(Sym.getIRName());
  485. }
  486. // Set the partition to external if we know it is re-defined by the linker
  487. // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
  488. // regular object, is referenced from llvm.compiler_used, or was already
  489. // recorded as being referenced from a different partition.
  490. if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
  491. (GlobalRes.Partition != GlobalResolution::Unknown &&
  492. GlobalRes.Partition != Partition)) {
  493. GlobalRes.Partition = GlobalResolution::External;
  494. } else
  495. // First recorded reference, save the current partition.
  496. GlobalRes.Partition = Partition;
  497. // Flag as visible outside of summary if visible from a regular object or
  498. // from a module that does not have a summary.
  499. GlobalRes.VisibleOutsideSummary |=
  500. (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
  501. }
  502. }
  503. static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
  504. ArrayRef<SymbolResolution> Res) {
  505. StringRef Path = Input->getName();
  506. OS << Path << '\n';
  507. auto ResI = Res.begin();
  508. for (const InputFile::Symbol &Sym : Input->symbols()) {
  509. assert(ResI != Res.end());
  510. SymbolResolution Res = *ResI++;
  511. OS << "-r=" << Path << ',' << Sym.getName() << ',';
  512. if (Res.Prevailing)
  513. OS << 'p';
  514. if (Res.FinalDefinitionInLinkageUnit)
  515. OS << 'l';
  516. if (Res.VisibleToRegularObj)
  517. OS << 'x';
  518. if (Res.LinkerRedefined)
  519. OS << 'r';
  520. OS << '\n';
  521. }
  522. OS.flush();
  523. assert(ResI == Res.end());
  524. }
  525. Error LTO::add(std::unique_ptr<InputFile> Input,
  526. ArrayRef<SymbolResolution> Res) {
  527. assert(!CalledGetMaxTasks);
  528. if (Conf.ResolutionFile)
  529. writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
  530. if (RegularLTO.CombinedModule->getTargetTriple().empty())
  531. RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
  532. const SymbolResolution *ResI = Res.begin();
  533. for (unsigned I = 0; I != Input->Mods.size(); ++I)
  534. if (Error Err = addModule(*Input, I, ResI, Res.end()))
  535. return Err;
  536. assert(ResI == Res.end());
  537. return Error::success();
  538. }
  539. Error LTO::addModule(InputFile &Input, unsigned ModI,
  540. const SymbolResolution *&ResI,
  541. const SymbolResolution *ResE) {
  542. Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
  543. if (!LTOInfo)
  544. return LTOInfo.takeError();
  545. if (EnableSplitLTOUnit.hasValue()) {
  546. // If only some modules were split, flag this in the index so that
  547. // we can skip or error on optimizations that need consistently split
  548. // modules (whole program devirt and lower type tests).
  549. if (EnableSplitLTOUnit.getValue() != LTOInfo->EnableSplitLTOUnit)
  550. ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
  551. } else
  552. EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
  553. BitcodeModule BM = Input.Mods[ModI];
  554. auto ModSyms = Input.module_symbols(ModI);
  555. addModuleToGlobalRes(ModSyms, {ResI, ResE},
  556. LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
  557. LTOInfo->HasSummary);
  558. if (LTOInfo->IsThinLTO)
  559. return addThinLTO(BM, ModSyms, ResI, ResE);
  560. RegularLTO.EmptyCombinedModule = false;
  561. Expected<RegularLTOState::AddedModule> ModOrErr =
  562. addRegularLTO(BM, ModSyms, ResI, ResE);
  563. if (!ModOrErr)
  564. return ModOrErr.takeError();
  565. if (!LTOInfo->HasSummary)
  566. return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
  567. // Regular LTO module summaries are added to a dummy module that represents
  568. // the combined regular LTO module.
  569. if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
  570. return Err;
  571. RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
  572. return Error::success();
  573. }
  574. // Checks whether the given global value is in a non-prevailing comdat
  575. // (comdat containing values the linker indicated were not prevailing,
  576. // which we then dropped to available_externally), and if so, removes
  577. // it from the comdat. This is called for all global values to ensure the
  578. // comdat is empty rather than leaving an incomplete comdat. It is needed for
  579. // regular LTO modules, in case we are in a mixed-LTO mode (both regular
  580. // and thin LTO modules) compilation. Since the regular LTO module will be
  581. // linked first in the final native link, we want to make sure the linker
  582. // doesn't select any of these incomplete comdats that would be left
  583. // in the regular LTO module without this cleanup.
  584. static void
  585. handleNonPrevailingComdat(GlobalValue &GV,
  586. std::set<const Comdat *> &NonPrevailingComdats) {
  587. Comdat *C = GV.getComdat();
  588. if (!C)
  589. return;
  590. if (!NonPrevailingComdats.count(C))
  591. return;
  592. // Additionally need to drop externally visible global values from the comdat
  593. // to available_externally, so that there aren't multiply defined linker
  594. // errors.
  595. if (!GV.hasLocalLinkage())
  596. GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
  597. if (auto GO = dyn_cast<GlobalObject>(&GV))
  598. GO->setComdat(nullptr);
  599. }
  600. // Add a regular LTO object to the link.
  601. // The resulting module needs to be linked into the combined LTO module with
  602. // linkRegularLTO.
  603. Expected<LTO::RegularLTOState::AddedModule>
  604. LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
  605. const SymbolResolution *&ResI,
  606. const SymbolResolution *ResE) {
  607. RegularLTOState::AddedModule Mod;
  608. Expected<std::unique_ptr<Module>> MOrErr =
  609. BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
  610. /*IsImporting*/ false);
  611. if (!MOrErr)
  612. return MOrErr.takeError();
  613. Module &M = **MOrErr;
  614. Mod.M = std::move(*MOrErr);
  615. if (Error Err = M.materializeMetadata())
  616. return std::move(Err);
  617. UpgradeDebugInfo(M);
  618. ModuleSymbolTable SymTab;
  619. SymTab.addModule(&M);
  620. for (GlobalVariable &GV : M.globals())
  621. if (GV.hasAppendingLinkage())
  622. Mod.Keep.push_back(&GV);
  623. DenseSet<GlobalObject *> AliasedGlobals;
  624. for (auto &GA : M.aliases())
  625. if (GlobalObject *GO = GA.getBaseObject())
  626. AliasedGlobals.insert(GO);
  627. // In this function we need IR GlobalValues matching the symbols in Syms
  628. // (which is not backed by a module), so we need to enumerate them in the same
  629. // order. The symbol enumeration order of a ModuleSymbolTable intentionally
  630. // matches the order of an irsymtab, but when we read the irsymtab in
  631. // InputFile::create we omit some symbols that are irrelevant to LTO. The
  632. // Skip() function skips the same symbols from the module as InputFile does
  633. // from the symbol table.
  634. auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
  635. auto Skip = [&]() {
  636. while (MsymI != MsymE) {
  637. auto Flags = SymTab.getSymbolFlags(*MsymI);
  638. if ((Flags & object::BasicSymbolRef::SF_Global) &&
  639. !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
  640. return;
  641. ++MsymI;
  642. }
  643. };
  644. Skip();
  645. std::set<const Comdat *> NonPrevailingComdats;
  646. for (const InputFile::Symbol &Sym : Syms) {
  647. assert(ResI != ResE);
  648. SymbolResolution Res = *ResI++;
  649. assert(MsymI != MsymE);
  650. ModuleSymbolTable::Symbol Msym = *MsymI++;
  651. Skip();
  652. if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
  653. if (Res.Prevailing) {
  654. if (Sym.isUndefined())
  655. continue;
  656. Mod.Keep.push_back(GV);
  657. // For symbols re-defined with linker -wrap and -defsym options,
  658. // set the linkage to weak to inhibit IPO. The linkage will be
  659. // restored by the linker.
  660. if (Res.LinkerRedefined)
  661. GV->setLinkage(GlobalValue::WeakAnyLinkage);
  662. GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
  663. if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
  664. GV->setLinkage(GlobalValue::getWeakLinkage(
  665. GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
  666. } else if (isa<GlobalObject>(GV) &&
  667. (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
  668. GV->hasAvailableExternallyLinkage()) &&
  669. !AliasedGlobals.count(cast<GlobalObject>(GV))) {
  670. // Any of the above three types of linkage indicates that the
  671. // chosen prevailing symbol will have the same semantics as this copy of
  672. // the symbol, so we may be able to link it with available_externally
  673. // linkage. We will decide later whether to do that when we link this
  674. // module (in linkRegularLTO), based on whether it is undefined.
  675. Mod.Keep.push_back(GV);
  676. GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
  677. if (GV->hasComdat())
  678. NonPrevailingComdats.insert(GV->getComdat());
  679. cast<GlobalObject>(GV)->setComdat(nullptr);
  680. }
  681. // Set the 'local' flag based on the linker resolution for this symbol.
  682. if (Res.FinalDefinitionInLinkageUnit) {
  683. GV->setDSOLocal(true);
  684. if (GV->hasDLLImportStorageClass())
  685. GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
  686. DefaultStorageClass);
  687. }
  688. }
  689. // Common resolution: collect the maximum size/alignment over all commons.
  690. // We also record if we see an instance of a common as prevailing, so that
  691. // if none is prevailing we can ignore it later.
  692. if (Sym.isCommon()) {
  693. // FIXME: We should figure out what to do about commons defined by asm.
  694. // For now they aren't reported correctly by ModuleSymbolTable.
  695. auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
  696. CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
  697. MaybeAlign SymAlign(Sym.getCommonAlignment());
  698. if (SymAlign)
  699. CommonRes.Align = max(*SymAlign, CommonRes.Align);
  700. CommonRes.Prevailing |= Res.Prevailing;
  701. }
  702. }
  703. if (!M.getComdatSymbolTable().empty())
  704. for (GlobalValue &GV : M.global_values())
  705. handleNonPrevailingComdat(GV, NonPrevailingComdats);
  706. assert(MsymI == MsymE);
  707. return std::move(Mod);
  708. }
  709. Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
  710. bool LivenessFromIndex) {
  711. std::vector<GlobalValue *> Keep;
  712. for (GlobalValue *GV : Mod.Keep) {
  713. if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
  714. if (Function *F = dyn_cast<Function>(GV)) {
  715. OptimizationRemarkEmitter ORE(F, nullptr);
  716. ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
  717. << ore::NV("Function", F)
  718. << " not added to the combined module ");
  719. }
  720. continue;
  721. }
  722. if (!GV->hasAvailableExternallyLinkage()) {
  723. Keep.push_back(GV);
  724. continue;
  725. }
  726. // Only link available_externally definitions if we don't already have a
  727. // definition.
  728. GlobalValue *CombinedGV =
  729. RegularLTO.CombinedModule->getNamedValue(GV->getName());
  730. if (CombinedGV && !CombinedGV->isDeclaration())
  731. continue;
  732. Keep.push_back(GV);
  733. }
  734. return RegularLTO.Mover->move(std::move(Mod.M), Keep,
  735. [](GlobalValue &, IRMover::ValueAdder) {},
  736. /* IsPerformingImport */ false);
  737. }
  738. // Add a ThinLTO module to the link.
  739. Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
  740. const SymbolResolution *&ResI,
  741. const SymbolResolution *ResE) {
  742. if (Error Err =
  743. BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
  744. ThinLTO.ModuleMap.size()))
  745. return Err;
  746. for (const InputFile::Symbol &Sym : Syms) {
  747. assert(ResI != ResE);
  748. SymbolResolution Res = *ResI++;
  749. if (!Sym.getIRName().empty()) {
  750. auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
  751. Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
  752. if (Res.Prevailing) {
  753. ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
  754. // For linker redefined symbols (via --wrap or --defsym) we want to
  755. // switch the linkage to `weak` to prevent IPOs from happening.
  756. // Find the summary in the module for this very GV and record the new
  757. // linkage so that we can switch it when we import the GV.
  758. if (Res.LinkerRedefined)
  759. if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
  760. GUID, BM.getModuleIdentifier()))
  761. S->setLinkage(GlobalValue::WeakAnyLinkage);
  762. }
  763. // If the linker resolved the symbol to a local definition then mark it
  764. // as local in the summary for the module we are adding.
  765. if (Res.FinalDefinitionInLinkageUnit) {
  766. if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
  767. GUID, BM.getModuleIdentifier())) {
  768. S->setDSOLocal(true);
  769. }
  770. }
  771. }
  772. }
  773. if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
  774. return make_error<StringError>(
  775. "Expected at most one ThinLTO module per bitcode file",
  776. inconvertibleErrorCode());
  777. if (!Conf.ThinLTOModulesToCompile.empty()) {
  778. if (!ThinLTO.ModulesToCompile)
  779. ThinLTO.ModulesToCompile = ModuleMapType();
  780. // This is a fuzzy name matching where only modules with name containing the
  781. // specified switch values are going to be compiled.
  782. for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
  783. if (BM.getModuleIdentifier().contains(Name)) {
  784. ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM});
  785. llvm::errs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier()
  786. << " to compile\n";
  787. }
  788. }
  789. }
  790. return Error::success();
  791. }
  792. unsigned LTO::getMaxTasks() const {
  793. CalledGetMaxTasks = true;
  794. auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
  795. : ThinLTO.ModuleMap.size();
  796. return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
  797. }
  798. // If only some of the modules were split, we cannot correctly handle
  799. // code that contains type tests or type checked loads.
  800. Error LTO::checkPartiallySplit() {
  801. if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
  802. return Error::success();
  803. Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
  804. Intrinsic::getName(Intrinsic::type_test));
  805. Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
  806. Intrinsic::getName(Intrinsic::type_checked_load));
  807. // First check if there are type tests / type checked loads in the
  808. // merged regular LTO module IR.
  809. if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
  810. (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
  811. return make_error<StringError>(
  812. "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
  813. inconvertibleErrorCode());
  814. // Otherwise check if there are any recorded in the combined summary from the
  815. // ThinLTO modules.
  816. for (auto &P : ThinLTO.CombinedIndex) {
  817. for (auto &S : P.second.SummaryList) {
  818. auto *FS = dyn_cast<FunctionSummary>(S.get());
  819. if (!FS)
  820. continue;
  821. if (!FS->type_test_assume_vcalls().empty() ||
  822. !FS->type_checked_load_vcalls().empty() ||
  823. !FS->type_test_assume_const_vcalls().empty() ||
  824. !FS->type_checked_load_const_vcalls().empty() ||
  825. !FS->type_tests().empty())
  826. return make_error<StringError>(
  827. "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
  828. inconvertibleErrorCode());
  829. }
  830. }
  831. return Error::success();
  832. }
  833. Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
  834. // Compute "dead" symbols, we don't want to import/export these!
  835. DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
  836. DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
  837. for (auto &Res : GlobalResolutions) {
  838. // Normally resolution have IR name of symbol. We can do nothing here
  839. // otherwise. See comments in GlobalResolution struct for more details.
  840. if (Res.second.IRName.empty())
  841. continue;
  842. GlobalValue::GUID GUID = GlobalValue::getGUID(
  843. GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
  844. if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
  845. GUIDPreservedSymbols.insert(GUID);
  846. GUIDPrevailingResolutions[GUID] =
  847. Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
  848. }
  849. auto isPrevailing = [&](GlobalValue::GUID G) {
  850. auto It = GUIDPrevailingResolutions.find(G);
  851. if (It == GUIDPrevailingResolutions.end())
  852. return PrevailingType::Unknown;
  853. return It->second;
  854. };
  855. computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
  856. isPrevailing, Conf.OptLevel > 0);
  857. // Setup output file to emit statistics.
  858. auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
  859. if (!StatsFileOrErr)
  860. return StatsFileOrErr.takeError();
  861. std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
  862. Error Result = runRegularLTO(AddStream);
  863. if (!Result)
  864. Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
  865. if (StatsFile)
  866. PrintStatisticsJSON(StatsFile->os());
  867. return Result;
  868. }
  869. Error LTO::runRegularLTO(AddStreamFn AddStream) {
  870. // Setup optimization remarks.
  871. auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
  872. RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
  873. Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness,
  874. Conf.RemarksHotnessThreshold);
  875. if (!DiagFileOrErr)
  876. return DiagFileOrErr.takeError();
  877. // Finalize linking of regular LTO modules containing summaries now that
  878. // we have computed liveness information.
  879. for (auto &M : RegularLTO.ModsWithSummaries)
  880. if (Error Err = linkRegularLTO(std::move(M),
  881. /*LivenessFromIndex=*/true))
  882. return Err;
  883. // Ensure we don't have inconsistently split LTO units with type tests.
  884. // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
  885. // this path both cases but eventually this should be split into two and
  886. // do the ThinLTO checks in `runThinLTO`.
  887. if (Error Err = checkPartiallySplit())
  888. return Err;
  889. // Make sure commons have the right size/alignment: we kept the largest from
  890. // all the prevailing when adding the inputs, and we apply it here.
  891. const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
  892. for (auto &I : RegularLTO.Commons) {
  893. if (!I.second.Prevailing)
  894. // Don't do anything if no instance of this common was prevailing.
  895. continue;
  896. GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
  897. if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
  898. // Don't create a new global if the type is already correct, just make
  899. // sure the alignment is correct.
  900. OldGV->setAlignment(I.second.Align);
  901. continue;
  902. }
  903. ArrayType *Ty =
  904. ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
  905. auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
  906. GlobalValue::CommonLinkage,
  907. ConstantAggregateZero::get(Ty), "");
  908. GV->setAlignment(I.second.Align);
  909. if (OldGV) {
  910. OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
  911. GV->takeName(OldGV);
  912. OldGV->eraseFromParent();
  913. } else {
  914. GV->setName(I.first);
  915. }
  916. }
  917. // If allowed, upgrade public vcall visibility metadata to linkage unit
  918. // visibility before whole program devirtualization in the optimizer.
  919. updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
  920. Conf.HasWholeProgramVisibility);
  921. if (Conf.PreOptModuleHook &&
  922. !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
  923. return Error::success();
  924. if (!Conf.CodeGenOnly) {
  925. for (const auto &R : GlobalResolutions) {
  926. if (!R.second.isPrevailingIRSymbol())
  927. continue;
  928. if (R.second.Partition != 0 &&
  929. R.second.Partition != GlobalResolution::External)
  930. continue;
  931. GlobalValue *GV =
  932. RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
  933. // Ignore symbols defined in other partitions.
  934. // Also skip declarations, which are not allowed to have internal linkage.
  935. if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
  936. continue;
  937. GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
  938. : GlobalValue::UnnamedAddr::None);
  939. if (EnableLTOInternalization && R.second.Partition == 0)
  940. GV->setLinkage(GlobalValue::InternalLinkage);
  941. }
  942. RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
  943. if (Conf.PostInternalizeModuleHook &&
  944. !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
  945. return Error::success();
  946. }
  947. if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
  948. if (Error Err = backend(
  949. Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
  950. std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex))
  951. return Err;
  952. }
  953. return finalizeOptimizationRemarks(std::move(*DiagFileOrErr));
  954. }
  955. static const char *libcallRoutineNames[] = {
  956. #define HANDLE_LIBCALL(code, name) name,
  957. #include "llvm/IR/RuntimeLibcalls.def"
  958. #undef HANDLE_LIBCALL
  959. };
  960. ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
  961. return makeArrayRef(libcallRoutineNames);
  962. }
  963. /// This class defines the interface to the ThinLTO backend.
  964. class lto::ThinBackendProc {
  965. protected:
  966. const Config &Conf;
  967. ModuleSummaryIndex &CombinedIndex;
  968. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
  969. public:
  970. ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
  971. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
  972. : Conf(Conf), CombinedIndex(CombinedIndex),
  973. ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
  974. virtual ~ThinBackendProc() {}
  975. virtual Error start(
  976. unsigned Task, BitcodeModule BM,
  977. const FunctionImporter::ImportMapTy &ImportList,
  978. const FunctionImporter::ExportSetTy &ExportList,
  979. const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
  980. MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
  981. virtual Error wait() = 0;
  982. virtual unsigned getThreadCount() = 0;
  983. };
  984. namespace {
  985. class InProcessThinBackend : public ThinBackendProc {
  986. ThreadPool BackendThreadPool;
  987. AddStreamFn AddStream;
  988. NativeObjectCache Cache;
  989. std::set<GlobalValue::GUID> CfiFunctionDefs;
  990. std::set<GlobalValue::GUID> CfiFunctionDecls;
  991. Optional<Error> Err;
  992. std::mutex ErrMu;
  993. public:
  994. InProcessThinBackend(
  995. const Config &Conf, ModuleSummaryIndex &CombinedIndex,
  996. ThreadPoolStrategy ThinLTOParallelism,
  997. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  998. AddStreamFn AddStream, NativeObjectCache Cache)
  999. : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
  1000. BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)),
  1001. Cache(std::move(Cache)) {
  1002. for (auto &Name : CombinedIndex.cfiFunctionDefs())
  1003. CfiFunctionDefs.insert(
  1004. GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
  1005. for (auto &Name : CombinedIndex.cfiFunctionDecls())
  1006. CfiFunctionDecls.insert(
  1007. GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
  1008. }
  1009. Error runThinLTOBackendThread(
  1010. AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
  1011. BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
  1012. const FunctionImporter::ImportMapTy &ImportList,
  1013. const FunctionImporter::ExportSetTy &ExportList,
  1014. const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
  1015. const GVSummaryMapTy &DefinedGlobals,
  1016. MapVector<StringRef, BitcodeModule> &ModuleMap) {
  1017. auto RunThinBackend = [&](AddStreamFn AddStream) {
  1018. LTOLLVMContext BackendContext(Conf);
  1019. Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
  1020. if (!MOrErr)
  1021. return MOrErr.takeError();
  1022. return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
  1023. ImportList, DefinedGlobals, ModuleMap);
  1024. };
  1025. auto ModuleID = BM.getModuleIdentifier();
  1026. if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
  1027. all_of(CombinedIndex.getModuleHash(ModuleID),
  1028. [](uint32_t V) { return V == 0; }))
  1029. // Cache disabled or no entry for this module in the combined index or
  1030. // no module hash.
  1031. return RunThinBackend(AddStream);
  1032. SmallString<40> Key;
  1033. // The module may be cached, this helps handling it.
  1034. computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
  1035. ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
  1036. CfiFunctionDecls);
  1037. if (AddStreamFn CacheAddStream = Cache(Task, Key))
  1038. return RunThinBackend(CacheAddStream);
  1039. return Error::success();
  1040. }
  1041. Error start(
  1042. unsigned Task, BitcodeModule BM,
  1043. const FunctionImporter::ImportMapTy &ImportList,
  1044. const FunctionImporter::ExportSetTy &ExportList,
  1045. const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
  1046. MapVector<StringRef, BitcodeModule> &ModuleMap) override {
  1047. StringRef ModulePath = BM.getModuleIdentifier();
  1048. assert(ModuleToDefinedGVSummaries.count(ModulePath));
  1049. const GVSummaryMapTy &DefinedGlobals =
  1050. ModuleToDefinedGVSummaries.find(ModulePath)->second;
  1051. BackendThreadPool.async(
  1052. [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
  1053. const FunctionImporter::ImportMapTy &ImportList,
  1054. const FunctionImporter::ExportSetTy &ExportList,
  1055. const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
  1056. &ResolvedODR,
  1057. const GVSummaryMapTy &DefinedGlobals,
  1058. MapVector<StringRef, BitcodeModule> &ModuleMap) {
  1059. if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
  1060. timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
  1061. "thin backend");
  1062. Error E = runThinLTOBackendThread(
  1063. AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
  1064. ResolvedODR, DefinedGlobals, ModuleMap);
  1065. if (E) {
  1066. std::unique_lock<std::mutex> L(ErrMu);
  1067. if (Err)
  1068. Err = joinErrors(std::move(*Err), std::move(E));
  1069. else
  1070. Err = std::move(E);
  1071. }
  1072. if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
  1073. timeTraceProfilerFinishThread();
  1074. },
  1075. BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
  1076. std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
  1077. return Error::success();
  1078. }
  1079. Error wait() override {
  1080. BackendThreadPool.wait();
  1081. if (Err)
  1082. return std::move(*Err);
  1083. else
  1084. return Error::success();
  1085. }
  1086. unsigned getThreadCount() override {
  1087. return BackendThreadPool.getThreadCount();
  1088. }
  1089. };
  1090. } // end anonymous namespace
  1091. ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism) {
  1092. return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
  1093. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  1094. AddStreamFn AddStream, NativeObjectCache Cache) {
  1095. return std::make_unique<InProcessThinBackend>(
  1096. Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, AddStream,
  1097. Cache);
  1098. };
  1099. }
  1100. // Given the original \p Path to an output file, replace any path
  1101. // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
  1102. // resulting directory if it does not yet exist.
  1103. std::string lto::getThinLTOOutputFile(const std::string &Path,
  1104. const std::string &OldPrefix,
  1105. const std::string &NewPrefix) {
  1106. if (OldPrefix.empty() && NewPrefix.empty())
  1107. return Path;
  1108. SmallString<128> NewPath(Path);
  1109. llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
  1110. StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
  1111. if (!ParentPath.empty()) {
  1112. // Make sure the new directory exists, creating it if necessary.
  1113. if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
  1114. llvm::errs() << "warning: could not create directory '" << ParentPath
  1115. << "': " << EC.message() << '\n';
  1116. }
  1117. return std::string(NewPath.str());
  1118. }
  1119. namespace {
  1120. class WriteIndexesThinBackend : public ThinBackendProc {
  1121. std::string OldPrefix, NewPrefix;
  1122. bool ShouldEmitImportsFiles;
  1123. raw_fd_ostream *LinkedObjectsFile;
  1124. lto::IndexWriteCallback OnWrite;
  1125. public:
  1126. WriteIndexesThinBackend(
  1127. const Config &Conf, ModuleSummaryIndex &CombinedIndex,
  1128. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  1129. std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
  1130. raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
  1131. : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
  1132. OldPrefix(OldPrefix), NewPrefix(NewPrefix),
  1133. ShouldEmitImportsFiles(ShouldEmitImportsFiles),
  1134. LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
  1135. Error start(
  1136. unsigned Task, BitcodeModule BM,
  1137. const FunctionImporter::ImportMapTy &ImportList,
  1138. const FunctionImporter::ExportSetTy &ExportList,
  1139. const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
  1140. MapVector<StringRef, BitcodeModule> &ModuleMap) override {
  1141. StringRef ModulePath = BM.getModuleIdentifier();
  1142. std::string NewModulePath =
  1143. getThinLTOOutputFile(std::string(ModulePath), OldPrefix, NewPrefix);
  1144. if (LinkedObjectsFile)
  1145. *LinkedObjectsFile << NewModulePath << '\n';
  1146. std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
  1147. gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
  1148. ImportList, ModuleToSummariesForIndex);
  1149. std::error_code EC;
  1150. raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
  1151. sys::fs::OpenFlags::OF_None);
  1152. if (EC)
  1153. return errorCodeToError(EC);
  1154. WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
  1155. if (ShouldEmitImportsFiles) {
  1156. EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
  1157. ModuleToSummariesForIndex);
  1158. if (EC)
  1159. return errorCodeToError(EC);
  1160. }
  1161. if (OnWrite)
  1162. OnWrite(std::string(ModulePath));
  1163. return Error::success();
  1164. }
  1165. Error wait() override { return Error::success(); }
  1166. // WriteIndexesThinBackend should always return 1 to prevent module
  1167. // re-ordering and avoid non-determinism in the final link.
  1168. unsigned getThreadCount() override { return 1; }
  1169. };
  1170. } // end anonymous namespace
  1171. ThinBackend lto::createWriteIndexesThinBackend(
  1172. std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
  1173. raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
  1174. return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
  1175. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  1176. AddStreamFn AddStream, NativeObjectCache Cache) {
  1177. return std::make_unique<WriteIndexesThinBackend>(
  1178. Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
  1179. ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
  1180. };
  1181. }
  1182. Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
  1183. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
  1184. if (ThinLTO.ModuleMap.empty())
  1185. return Error::success();
  1186. if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
  1187. llvm::errs() << "warning: [ThinLTO] No module compiled\n";
  1188. return Error::success();
  1189. }
  1190. if (Conf.CombinedIndexHook &&
  1191. !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
  1192. return Error::success();
  1193. // Collect for each module the list of function it defines (GUID ->
  1194. // Summary).
  1195. StringMap<GVSummaryMapTy>
  1196. ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
  1197. ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
  1198. ModuleToDefinedGVSummaries);
  1199. // Create entries for any modules that didn't have any GV summaries
  1200. // (either they didn't have any GVs to start with, or we suppressed
  1201. // generation of the summaries because they e.g. had inline assembly
  1202. // uses that couldn't be promoted/renamed on export). This is so
  1203. // InProcessThinBackend::start can still launch a backend thread, which
  1204. // is passed the map of summaries for the module, without any special
  1205. // handling for this case.
  1206. for (auto &Mod : ThinLTO.ModuleMap)
  1207. if (!ModuleToDefinedGVSummaries.count(Mod.first))
  1208. ModuleToDefinedGVSummaries.try_emplace(Mod.first);
  1209. // Synthesize entry counts for functions in the CombinedIndex.
  1210. computeSyntheticCounts(ThinLTO.CombinedIndex);
  1211. StringMap<FunctionImporter::ImportMapTy> ImportLists(
  1212. ThinLTO.ModuleMap.size());
  1213. StringMap<FunctionImporter::ExportSetTy> ExportLists(
  1214. ThinLTO.ModuleMap.size());
  1215. StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
  1216. if (DumpThinCGSCCs)
  1217. ThinLTO.CombinedIndex.dumpSCCs(outs());
  1218. std::set<GlobalValue::GUID> ExportedGUIDs;
  1219. // If allowed, upgrade public vcall visibility to linkage unit visibility in
  1220. // the summaries before whole program devirtualization below.
  1221. updateVCallVisibilityInIndex(ThinLTO.CombinedIndex,
  1222. Conf.HasWholeProgramVisibility);
  1223. // Perform index-based WPD. This will return immediately if there are
  1224. // no index entries in the typeIdMetadata map (e.g. if we are instead
  1225. // performing IR-based WPD in hybrid regular/thin LTO mode).
  1226. std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
  1227. runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
  1228. LocalWPDTargetsMap);
  1229. if (Conf.OptLevel > 0)
  1230. ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
  1231. ImportLists, ExportLists);
  1232. // Figure out which symbols need to be internalized. This also needs to happen
  1233. // at -O0 because summary-based DCE is implemented using internalization, and
  1234. // we must apply DCE consistently with the full LTO module in order to avoid
  1235. // undefined references during the final link.
  1236. for (auto &Res : GlobalResolutions) {
  1237. // If the symbol does not have external references or it is not prevailing,
  1238. // then not need to mark it as exported from a ThinLTO partition.
  1239. if (Res.second.Partition != GlobalResolution::External ||
  1240. !Res.second.isPrevailingIRSymbol())
  1241. continue;
  1242. auto GUID = GlobalValue::getGUID(
  1243. GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
  1244. // Mark exported unless index-based analysis determined it to be dead.
  1245. if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
  1246. ExportedGUIDs.insert(GUID);
  1247. }
  1248. // Any functions referenced by the jump table in the regular LTO object must
  1249. // be exported.
  1250. for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
  1251. ExportedGUIDs.insert(
  1252. GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
  1253. auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
  1254. const auto &ExportList = ExportLists.find(ModuleIdentifier);
  1255. return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
  1256. ExportedGUIDs.count(VI.getGUID());
  1257. };
  1258. // Update local devirtualized targets that were exported by cross-module
  1259. // importing or by other devirtualizations marked in the ExportedGUIDs set.
  1260. updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
  1261. LocalWPDTargetsMap);
  1262. auto isPrevailing = [&](GlobalValue::GUID GUID,
  1263. const GlobalValueSummary *S) {
  1264. return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
  1265. };
  1266. thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
  1267. isPrevailing);
  1268. auto recordNewLinkage = [&](StringRef ModuleIdentifier,
  1269. GlobalValue::GUID GUID,
  1270. GlobalValue::LinkageTypes NewLinkage) {
  1271. ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
  1272. };
  1273. thinLTOResolvePrevailingInIndex(ThinLTO.CombinedIndex, isPrevailing,
  1274. recordNewLinkage, GUIDPreservedSymbols);
  1275. generateParamAccessSummary(ThinLTO.CombinedIndex);
  1276. std::unique_ptr<ThinBackendProc> BackendProc =
  1277. ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
  1278. AddStream, Cache);
  1279. auto &ModuleMap =
  1280. ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
  1281. auto ProcessOneModule = [&](int I) -> Error {
  1282. auto &Mod = *(ModuleMap.begin() + I);
  1283. // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
  1284. // combined module and parallel code generation partitions.
  1285. return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I,
  1286. Mod.second, ImportLists[Mod.first],
  1287. ExportLists[Mod.first], ResolvedODR[Mod.first],
  1288. ThinLTO.ModuleMap);
  1289. };
  1290. if (BackendProc->getThreadCount() == 1) {
  1291. // Process the modules in the order they were provided on the command-line.
  1292. // It is important for this codepath to be used for WriteIndexesThinBackend,
  1293. // to ensure the emitted LinkedObjectsFile lists ThinLTO objects in the same
  1294. // order as the inputs, which otherwise would affect the final link order.
  1295. for (int I = 0, E = ModuleMap.size(); I != E; ++I)
  1296. if (Error E = ProcessOneModule(I))
  1297. return E;
  1298. } else {
  1299. // When executing in parallel, process largest bitsize modules first to
  1300. // improve parallelism, and avoid starving the thread pool near the end.
  1301. // This saves about 15 sec on a 36-core machine while link `clang.exe` (out
  1302. // of 100 sec).
  1303. std::vector<BitcodeModule *> ModulesVec;
  1304. ModulesVec.reserve(ModuleMap.size());
  1305. for (auto &Mod : ModuleMap)
  1306. ModulesVec.push_back(&Mod.second);
  1307. for (int I : generateModulesOrdering(ModulesVec))
  1308. if (Error E = ProcessOneModule(I))
  1309. return E;
  1310. }
  1311. return BackendProc->wait();
  1312. }
  1313. Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
  1314. LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
  1315. StringRef RemarksFormat, bool RemarksWithHotness,
  1316. Optional<uint64_t> RemarksHotnessThreshold, int Count) {
  1317. std::string Filename = std::string(RemarksFilename);
  1318. // For ThinLTO, file.opt.<format> becomes
  1319. // file.opt.<format>.thin.<num>.<format>.
  1320. if (!Filename.empty() && Count != -1)
  1321. Filename =
  1322. (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
  1323. .str();
  1324. auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
  1325. Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
  1326. RemarksHotnessThreshold);
  1327. if (Error E = ResultOrErr.takeError())
  1328. return std::move(E);
  1329. if (*ResultOrErr)
  1330. (*ResultOrErr)->keep();
  1331. return ResultOrErr;
  1332. }
  1333. Expected<std::unique_ptr<ToolOutputFile>>
  1334. lto::setupStatsFile(StringRef StatsFilename) {
  1335. // Setup output file to emit statistics.
  1336. if (StatsFilename.empty())
  1337. return nullptr;
  1338. llvm::EnableStatistics(false);
  1339. std::error_code EC;
  1340. auto StatsFile =
  1341. std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
  1342. if (EC)
  1343. return errorCodeToError(EC);
  1344. StatsFile->keep();
  1345. return std::move(StatsFile);
  1346. }
  1347. // Compute the ordering we will process the inputs: the rough heuristic here
  1348. // is to sort them per size so that the largest module get schedule as soon as
  1349. // possible. This is purely a compile-time optimization.
  1350. std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
  1351. std::vector<int> ModulesOrdering;
  1352. ModulesOrdering.resize(R.size());
  1353. std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
  1354. llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
  1355. auto LSize = R[LeftIndex]->getBuffer().size();
  1356. auto RSize = R[RightIndex]->getBuffer().size();
  1357. return LSize > RSize;
  1358. });
  1359. return ModulesOrdering;
  1360. }