ModuleSummaryIndex.h 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ModuleSummaryIndex.h - Module Summary Index ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// @file
  15. /// ModuleSummaryIndex.h This file contains the declarations the classes that
  16. /// hold the module index and summary for function importing.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_IR_MODULESUMMARYINDEX_H
  20. #define LLVM_IR_MODULESUMMARYINDEX_H
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. #include "llvm/ADT/StringMap.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/IR/ConstantRange.h"
  29. #include "llvm/IR/GlobalValue.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/Support/Allocator.h"
  32. #include "llvm/Support/MathExtras.h"
  33. #include "llvm/Support/ScaledNumber.h"
  34. #include "llvm/Support/StringSaver.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <algorithm>
  37. #include <array>
  38. #include <cassert>
  39. #include <cstddef>
  40. #include <cstdint>
  41. #include <map>
  42. #include <memory>
  43. #include <set>
  44. #include <string>
  45. #include <utility>
  46. #include <vector>
  47. namespace llvm {
  48. template <class GraphType> struct GraphTraits;
  49. namespace yaml {
  50. template <typename T> struct MappingTraits;
  51. } // end namespace yaml
  52. /// Class to accumulate and hold information about a callee.
  53. struct CalleeInfo {
  54. enum class HotnessType : uint8_t {
  55. Unknown = 0,
  56. Cold = 1,
  57. None = 2,
  58. Hot = 3,
  59. Critical = 4
  60. };
  61. // The size of the bit-field might need to be adjusted if more values are
  62. // added to HotnessType enum.
  63. uint32_t Hotness : 3;
  64. /// The value stored in RelBlockFreq has to be interpreted as the digits of
  65. /// a scaled number with a scale of \p -ScaleShift.
  66. uint32_t RelBlockFreq : 29;
  67. static constexpr int32_t ScaleShift = 8;
  68. static constexpr uint64_t MaxRelBlockFreq = (1 << 29) - 1;
  69. CalleeInfo()
  70. : Hotness(static_cast<uint32_t>(HotnessType::Unknown)), RelBlockFreq(0) {}
  71. explicit CalleeInfo(HotnessType Hotness, uint64_t RelBF)
  72. : Hotness(static_cast<uint32_t>(Hotness)), RelBlockFreq(RelBF) {}
  73. void updateHotness(const HotnessType OtherHotness) {
  74. Hotness = std::max(Hotness, static_cast<uint32_t>(OtherHotness));
  75. }
  76. HotnessType getHotness() const { return HotnessType(Hotness); }
  77. /// Update \p RelBlockFreq from \p BlockFreq and \p EntryFreq
  78. ///
  79. /// BlockFreq is divided by EntryFreq and added to RelBlockFreq. To represent
  80. /// fractional values, the result is represented as a fixed point number with
  81. /// scale of -ScaleShift.
  82. void updateRelBlockFreq(uint64_t BlockFreq, uint64_t EntryFreq) {
  83. if (EntryFreq == 0)
  84. return;
  85. using Scaled64 = ScaledNumber<uint64_t>;
  86. Scaled64 Temp(BlockFreq, ScaleShift);
  87. Temp /= Scaled64::get(EntryFreq);
  88. uint64_t Sum =
  89. SaturatingAdd<uint64_t>(Temp.toInt<uint64_t>(), RelBlockFreq);
  90. Sum = std::min(Sum, uint64_t(MaxRelBlockFreq));
  91. RelBlockFreq = static_cast<uint32_t>(Sum);
  92. }
  93. };
  94. inline const char *getHotnessName(CalleeInfo::HotnessType HT) {
  95. switch (HT) {
  96. case CalleeInfo::HotnessType::Unknown:
  97. return "unknown";
  98. case CalleeInfo::HotnessType::Cold:
  99. return "cold";
  100. case CalleeInfo::HotnessType::None:
  101. return "none";
  102. case CalleeInfo::HotnessType::Hot:
  103. return "hot";
  104. case CalleeInfo::HotnessType::Critical:
  105. return "critical";
  106. }
  107. llvm_unreachable("invalid hotness");
  108. }
  109. class GlobalValueSummary;
  110. using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>;
  111. struct alignas(8) GlobalValueSummaryInfo {
  112. union NameOrGV {
  113. NameOrGV(bool HaveGVs) {
  114. if (HaveGVs)
  115. GV = nullptr;
  116. else
  117. Name = "";
  118. }
  119. /// The GlobalValue corresponding to this summary. This is only used in
  120. /// per-module summaries and when the IR is available. E.g. when module
  121. /// analysis is being run, or when parsing both the IR and the summary
  122. /// from assembly.
  123. const GlobalValue *GV;
  124. /// Summary string representation. This StringRef points to BC module
  125. /// string table and is valid until module data is stored in memory.
  126. /// This is guaranteed to happen until runThinLTOBackend function is
  127. /// called, so it is safe to use this field during thin link. This field
  128. /// is only valid if summary index was loaded from BC file.
  129. StringRef Name;
  130. } U;
  131. GlobalValueSummaryInfo(bool HaveGVs) : U(HaveGVs) {}
  132. /// List of global value summary structures for a particular value held
  133. /// in the GlobalValueMap. Requires a vector in the case of multiple
  134. /// COMDAT values of the same name.
  135. GlobalValueSummaryList SummaryList;
  136. };
  137. /// Map from global value GUID to corresponding summary structures. Use a
  138. /// std::map rather than a DenseMap so that pointers to the map's value_type
  139. /// (which are used by ValueInfo) are not invalidated by insertion. Also it will
  140. /// likely incur less overhead, as the value type is not very small and the size
  141. /// of the map is unknown, resulting in inefficiencies due to repeated
  142. /// insertions and resizing.
  143. using GlobalValueSummaryMapTy =
  144. std::map<GlobalValue::GUID, GlobalValueSummaryInfo>;
  145. /// Struct that holds a reference to a particular GUID in a global value
  146. /// summary.
  147. struct ValueInfo {
  148. enum Flags { HaveGV = 1, ReadOnly = 2, WriteOnly = 4 };
  149. PointerIntPair<const GlobalValueSummaryMapTy::value_type *, 3, int>
  150. RefAndFlags;
  151. ValueInfo() = default;
  152. ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R) {
  153. RefAndFlags.setPointer(R);
  154. RefAndFlags.setInt(HaveGVs);
  155. }
  156. explicit operator bool() const { return getRef(); }
  157. GlobalValue::GUID getGUID() const { return getRef()->first; }
  158. const GlobalValue *getValue() const {
  159. assert(haveGVs());
  160. return getRef()->second.U.GV;
  161. }
  162. ArrayRef<std::unique_ptr<GlobalValueSummary>> getSummaryList() const {
  163. return getRef()->second.SummaryList;
  164. }
  165. StringRef name() const {
  166. return haveGVs() ? getRef()->second.U.GV->getName()
  167. : getRef()->second.U.Name;
  168. }
  169. bool haveGVs() const { return RefAndFlags.getInt() & HaveGV; }
  170. bool isReadOnly() const {
  171. assert(isValidAccessSpecifier());
  172. return RefAndFlags.getInt() & ReadOnly;
  173. }
  174. bool isWriteOnly() const {
  175. assert(isValidAccessSpecifier());
  176. return RefAndFlags.getInt() & WriteOnly;
  177. }
  178. unsigned getAccessSpecifier() const {
  179. assert(isValidAccessSpecifier());
  180. return RefAndFlags.getInt() & (ReadOnly | WriteOnly);
  181. }
  182. bool isValidAccessSpecifier() const {
  183. unsigned BadAccessMask = ReadOnly | WriteOnly;
  184. return (RefAndFlags.getInt() & BadAccessMask) != BadAccessMask;
  185. }
  186. void setReadOnly() {
  187. // We expect ro/wo attribute to set only once during
  188. // ValueInfo lifetime.
  189. assert(getAccessSpecifier() == 0);
  190. RefAndFlags.setInt(RefAndFlags.getInt() | ReadOnly);
  191. }
  192. void setWriteOnly() {
  193. assert(getAccessSpecifier() == 0);
  194. RefAndFlags.setInt(RefAndFlags.getInt() | WriteOnly);
  195. }
  196. const GlobalValueSummaryMapTy::value_type *getRef() const {
  197. return RefAndFlags.getPointer();
  198. }
  199. /// Returns the most constraining visibility among summaries. The
  200. /// visibilities, ordered from least to most constraining, are: default,
  201. /// protected and hidden.
  202. GlobalValue::VisibilityTypes getELFVisibility() const;
  203. /// Checks if all summaries are DSO local (have the flag set). When DSOLocal
  204. /// propagation has been done, set the parameter to enable fast check.
  205. bool isDSOLocal(bool WithDSOLocalPropagation = false) const;
  206. /// Checks if all copies are eligible for auto-hiding (have flag set).
  207. bool canAutoHide() const;
  208. };
  209. inline raw_ostream &operator<<(raw_ostream &OS, const ValueInfo &VI) {
  210. OS << VI.getGUID();
  211. if (!VI.name().empty())
  212. OS << " (" << VI.name() << ")";
  213. return OS;
  214. }
  215. inline bool operator==(const ValueInfo &A, const ValueInfo &B) {
  216. assert(A.getRef() && B.getRef() &&
  217. "Need ValueInfo with non-null Ref for comparison");
  218. return A.getRef() == B.getRef();
  219. }
  220. inline bool operator!=(const ValueInfo &A, const ValueInfo &B) {
  221. assert(A.getRef() && B.getRef() &&
  222. "Need ValueInfo with non-null Ref for comparison");
  223. return A.getRef() != B.getRef();
  224. }
  225. inline bool operator<(const ValueInfo &A, const ValueInfo &B) {
  226. assert(A.getRef() && B.getRef() &&
  227. "Need ValueInfo with non-null Ref to compare GUIDs");
  228. return A.getGUID() < B.getGUID();
  229. }
  230. template <> struct DenseMapInfo<ValueInfo> {
  231. static inline ValueInfo getEmptyKey() {
  232. return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
  233. }
  234. static inline ValueInfo getTombstoneKey() {
  235. return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-16);
  236. }
  237. static inline bool isSpecialKey(ValueInfo V) {
  238. return V == getTombstoneKey() || V == getEmptyKey();
  239. }
  240. static bool isEqual(ValueInfo L, ValueInfo R) {
  241. // We are not supposed to mix ValueInfo(s) with different HaveGVs flag
  242. // in a same container.
  243. assert(isSpecialKey(L) || isSpecialKey(R) || (L.haveGVs() == R.haveGVs()));
  244. return L.getRef() == R.getRef();
  245. }
  246. static unsigned getHashValue(ValueInfo I) { return (uintptr_t)I.getRef(); }
  247. };
  248. /// Function and variable summary information to aid decisions and
  249. /// implementation of importing.
  250. class GlobalValueSummary {
  251. public:
  252. /// Sububclass discriminator (for dyn_cast<> et al.)
  253. enum SummaryKind : unsigned { AliasKind, FunctionKind, GlobalVarKind };
  254. /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
  255. struct GVFlags {
  256. /// The linkage type of the associated global value.
  257. ///
  258. /// One use is to flag values that have local linkage types and need to
  259. /// have module identifier appended before placing into the combined
  260. /// index, to disambiguate from other values with the same name.
  261. /// In the future this will be used to update and optimize linkage
  262. /// types based on global summary-based analysis.
  263. unsigned Linkage : 4;
  264. /// Indicates the visibility.
  265. unsigned Visibility : 2;
  266. /// Indicate if the global value cannot be imported (e.g. it cannot
  267. /// be renamed or references something that can't be renamed).
  268. unsigned NotEligibleToImport : 1;
  269. /// In per-module summary, indicate that the global value must be considered
  270. /// a live root for index-based liveness analysis. Used for special LLVM
  271. /// values such as llvm.global_ctors that the linker does not know about.
  272. ///
  273. /// In combined summary, indicate that the global value is live.
  274. unsigned Live : 1;
  275. /// Indicates that the linker resolved the symbol to a definition from
  276. /// within the same linkage unit.
  277. unsigned DSOLocal : 1;
  278. /// In the per-module summary, indicates that the global value is
  279. /// linkonce_odr and global unnamed addr (so eligible for auto-hiding
  280. /// via hidden visibility). In the combined summary, indicates that the
  281. /// prevailing linkonce_odr copy can be auto-hidden via hidden visibility
  282. /// when it is upgraded to weak_odr in the backend. This is legal when
  283. /// all copies are eligible for auto-hiding (i.e. all copies were
  284. /// linkonce_odr global unnamed addr. If any copy is not (e.g. it was
  285. /// originally weak_odr, we cannot auto-hide the prevailing copy as it
  286. /// means the symbol was externally visible.
  287. unsigned CanAutoHide : 1;
  288. /// Convenience Constructors
  289. explicit GVFlags(GlobalValue::LinkageTypes Linkage,
  290. GlobalValue::VisibilityTypes Visibility,
  291. bool NotEligibleToImport, bool Live, bool IsLocal,
  292. bool CanAutoHide)
  293. : Linkage(Linkage), Visibility(Visibility),
  294. NotEligibleToImport(NotEligibleToImport), Live(Live),
  295. DSOLocal(IsLocal), CanAutoHide(CanAutoHide) {}
  296. };
  297. private:
  298. /// Kind of summary for use in dyn_cast<> et al.
  299. SummaryKind Kind;
  300. GVFlags Flags;
  301. /// This is the hash of the name of the symbol in the original file. It is
  302. /// identical to the GUID for global symbols, but differs for local since the
  303. /// GUID includes the module level id in the hash.
  304. GlobalValue::GUID OriginalName = 0;
  305. /// Path of module IR containing value's definition, used to locate
  306. /// module during importing.
  307. ///
  308. /// This is only used during parsing of the combined index, or when
  309. /// parsing the per-module index for creation of the combined summary index,
  310. /// not during writing of the per-module index which doesn't contain a
  311. /// module path string table.
  312. StringRef ModulePath;
  313. /// List of values referenced by this global value's definition
  314. /// (either by the initializer of a global variable, or referenced
  315. /// from within a function). This does not include functions called, which
  316. /// are listed in the derived FunctionSummary object.
  317. std::vector<ValueInfo> RefEdgeList;
  318. protected:
  319. GlobalValueSummary(SummaryKind K, GVFlags Flags, std::vector<ValueInfo> Refs)
  320. : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {
  321. assert((K != AliasKind || Refs.empty()) &&
  322. "Expect no references for AliasSummary");
  323. }
  324. public:
  325. virtual ~GlobalValueSummary() = default;
  326. /// Returns the hash of the original name, it is identical to the GUID for
  327. /// externally visible symbols, but not for local ones.
  328. GlobalValue::GUID getOriginalName() const { return OriginalName; }
  329. /// Initialize the original name hash in this summary.
  330. void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
  331. /// Which kind of summary subclass this is.
  332. SummaryKind getSummaryKind() const { return Kind; }
  333. /// Set the path to the module containing this function, for use in
  334. /// the combined index.
  335. void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
  336. /// Get the path to the module containing this function.
  337. StringRef modulePath() const { return ModulePath; }
  338. /// Get the flags for this GlobalValue (see \p struct GVFlags).
  339. GVFlags flags() const { return Flags; }
  340. /// Return linkage type recorded for this global value.
  341. GlobalValue::LinkageTypes linkage() const {
  342. return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
  343. }
  344. /// Sets the linkage to the value determined by global summary-based
  345. /// optimization. Will be applied in the ThinLTO backends.
  346. void setLinkage(GlobalValue::LinkageTypes Linkage) {
  347. Flags.Linkage = Linkage;
  348. }
  349. /// Return true if this global value can't be imported.
  350. bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
  351. bool isLive() const { return Flags.Live; }
  352. void setLive(bool Live) { Flags.Live = Live; }
  353. void setDSOLocal(bool Local) { Flags.DSOLocal = Local; }
  354. bool isDSOLocal() const { return Flags.DSOLocal; }
  355. void setCanAutoHide(bool CanAutoHide) { Flags.CanAutoHide = CanAutoHide; }
  356. bool canAutoHide() const { return Flags.CanAutoHide; }
  357. GlobalValue::VisibilityTypes getVisibility() const {
  358. return (GlobalValue::VisibilityTypes)Flags.Visibility;
  359. }
  360. void setVisibility(GlobalValue::VisibilityTypes Vis) {
  361. Flags.Visibility = (unsigned)Vis;
  362. }
  363. /// Flag that this global value cannot be imported.
  364. void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
  365. /// Return the list of values referenced by this global value definition.
  366. ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
  367. /// If this is an alias summary, returns the summary of the aliased object (a
  368. /// global variable or function), otherwise returns itself.
  369. GlobalValueSummary *getBaseObject();
  370. const GlobalValueSummary *getBaseObject() const;
  371. friend class ModuleSummaryIndex;
  372. };
  373. /// Alias summary information.
  374. class AliasSummary : public GlobalValueSummary {
  375. ValueInfo AliaseeValueInfo;
  376. /// This is the Aliasee in the same module as alias (could get from VI, trades
  377. /// memory for time). Note that this pointer may be null (and the value info
  378. /// empty) when we have a distributed index where the alias is being imported
  379. /// (as a copy of the aliasee), but the aliasee is not.
  380. GlobalValueSummary *AliaseeSummary;
  381. public:
  382. AliasSummary(GVFlags Flags)
  383. : GlobalValueSummary(AliasKind, Flags, ArrayRef<ValueInfo>{}),
  384. AliaseeSummary(nullptr) {}
  385. /// Check if this is an alias summary.
  386. static bool classof(const GlobalValueSummary *GVS) {
  387. return GVS->getSummaryKind() == AliasKind;
  388. }
  389. void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee) {
  390. AliaseeValueInfo = AliaseeVI;
  391. AliaseeSummary = Aliasee;
  392. }
  393. bool hasAliasee() const {
  394. assert(!!AliaseeSummary == (AliaseeValueInfo &&
  395. !AliaseeValueInfo.getSummaryList().empty()) &&
  396. "Expect to have both aliasee summary and summary list or neither");
  397. return !!AliaseeSummary;
  398. }
  399. const GlobalValueSummary &getAliasee() const {
  400. assert(AliaseeSummary && "Unexpected missing aliasee summary");
  401. return *AliaseeSummary;
  402. }
  403. GlobalValueSummary &getAliasee() {
  404. return const_cast<GlobalValueSummary &>(
  405. static_cast<const AliasSummary *>(this)->getAliasee());
  406. }
  407. ValueInfo getAliaseeVI() const {
  408. assert(AliaseeValueInfo && "Unexpected missing aliasee");
  409. return AliaseeValueInfo;
  410. }
  411. GlobalValue::GUID getAliaseeGUID() const {
  412. assert(AliaseeValueInfo && "Unexpected missing aliasee");
  413. return AliaseeValueInfo.getGUID();
  414. }
  415. };
  416. const inline GlobalValueSummary *GlobalValueSummary::getBaseObject() const {
  417. if (auto *AS = dyn_cast<AliasSummary>(this))
  418. return &AS->getAliasee();
  419. return this;
  420. }
  421. inline GlobalValueSummary *GlobalValueSummary::getBaseObject() {
  422. if (auto *AS = dyn_cast<AliasSummary>(this))
  423. return &AS->getAliasee();
  424. return this;
  425. }
  426. /// Function summary information to aid decisions and implementation of
  427. /// importing.
  428. class FunctionSummary : public GlobalValueSummary {
  429. public:
  430. /// <CalleeValueInfo, CalleeInfo> call edge pair.
  431. using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
  432. /// Types for -force-summary-edges-cold debugging option.
  433. enum ForceSummaryHotnessType : unsigned {
  434. FSHT_None,
  435. FSHT_AllNonCritical,
  436. FSHT_All
  437. };
  438. /// An "identifier" for a virtual function. This contains the type identifier
  439. /// represented as a GUID and the offset from the address point to the virtual
  440. /// function pointer, where "address point" is as defined in the Itanium ABI:
  441. /// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
  442. struct VFuncId {
  443. GlobalValue::GUID GUID;
  444. uint64_t Offset;
  445. };
  446. /// A specification for a virtual function call with all constant integer
  447. /// arguments. This is used to perform virtual constant propagation on the
  448. /// summary.
  449. struct ConstVCall {
  450. VFuncId VFunc;
  451. std::vector<uint64_t> Args;
  452. };
  453. /// All type identifier related information. Because these fields are
  454. /// relatively uncommon we only allocate space for them if necessary.
  455. struct TypeIdInfo {
  456. /// List of type identifiers used by this function in llvm.type.test
  457. /// intrinsics referenced by something other than an llvm.assume intrinsic,
  458. /// represented as GUIDs.
  459. std::vector<GlobalValue::GUID> TypeTests;
  460. /// List of virtual calls made by this function using (respectively)
  461. /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
  462. /// not have all constant integer arguments.
  463. std::vector<VFuncId> TypeTestAssumeVCalls, TypeCheckedLoadVCalls;
  464. /// List of virtual calls made by this function using (respectively)
  465. /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
  466. /// all constant integer arguments.
  467. std::vector<ConstVCall> TypeTestAssumeConstVCalls,
  468. TypeCheckedLoadConstVCalls;
  469. };
  470. /// Flags specific to function summaries.
  471. struct FFlags {
  472. // Function attribute flags. Used to track if a function accesses memory,
  473. // recurses or aliases.
  474. unsigned ReadNone : 1;
  475. unsigned ReadOnly : 1;
  476. unsigned NoRecurse : 1;
  477. unsigned ReturnDoesNotAlias : 1;
  478. // Indicate if the global value cannot be inlined.
  479. unsigned NoInline : 1;
  480. // Indicate if function should be always inlined.
  481. unsigned AlwaysInline : 1;
  482. // Indicate if function never raises an exception. Can be modified during
  483. // thinlink function attribute propagation
  484. unsigned NoUnwind : 1;
  485. // Indicate if function contains instructions that mayThrow
  486. unsigned MayThrow : 1;
  487. // If there are calls to unknown targets (e.g. indirect)
  488. unsigned HasUnknownCall : 1;
  489. // Indicate if a function must be an unreachable function.
  490. //
  491. // This bit is sufficient but not necessary;
  492. // if this bit is on, the function must be regarded as unreachable;
  493. // if this bit is off, the function might be reachable or unreachable.
  494. unsigned MustBeUnreachable : 1;
  495. FFlags &operator&=(const FFlags &RHS) {
  496. this->ReadNone &= RHS.ReadNone;
  497. this->ReadOnly &= RHS.ReadOnly;
  498. this->NoRecurse &= RHS.NoRecurse;
  499. this->ReturnDoesNotAlias &= RHS.ReturnDoesNotAlias;
  500. this->NoInline &= RHS.NoInline;
  501. this->AlwaysInline &= RHS.AlwaysInline;
  502. this->NoUnwind &= RHS.NoUnwind;
  503. this->MayThrow &= RHS.MayThrow;
  504. this->HasUnknownCall &= RHS.HasUnknownCall;
  505. this->MustBeUnreachable &= RHS.MustBeUnreachable;
  506. return *this;
  507. }
  508. bool anyFlagSet() {
  509. return this->ReadNone | this->ReadOnly | this->NoRecurse |
  510. this->ReturnDoesNotAlias | this->NoInline | this->AlwaysInline |
  511. this->NoUnwind | this->MayThrow | this->HasUnknownCall |
  512. this->MustBeUnreachable;
  513. }
  514. operator std::string() {
  515. std::string Output;
  516. raw_string_ostream OS(Output);
  517. OS << "funcFlags: (";
  518. OS << "readNone: " << this->ReadNone;
  519. OS << ", readOnly: " << this->ReadOnly;
  520. OS << ", noRecurse: " << this->NoRecurse;
  521. OS << ", returnDoesNotAlias: " << this->ReturnDoesNotAlias;
  522. OS << ", noInline: " << this->NoInline;
  523. OS << ", alwaysInline: " << this->AlwaysInline;
  524. OS << ", noUnwind: " << this->NoUnwind;
  525. OS << ", mayThrow: " << this->MayThrow;
  526. OS << ", hasUnknownCall: " << this->HasUnknownCall;
  527. OS << ", mustBeUnreachable: " << this->MustBeUnreachable;
  528. OS << ")";
  529. return OS.str();
  530. }
  531. };
  532. /// Describes the uses of a parameter by the function.
  533. struct ParamAccess {
  534. static constexpr uint32_t RangeWidth = 64;
  535. /// Describes the use of a value in a call instruction, specifying the
  536. /// call's target, the value's parameter number, and the possible range of
  537. /// offsets from the beginning of the value that are passed.
  538. struct Call {
  539. uint64_t ParamNo = 0;
  540. ValueInfo Callee;
  541. ConstantRange Offsets{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
  542. Call() = default;
  543. Call(uint64_t ParamNo, ValueInfo Callee, const ConstantRange &Offsets)
  544. : ParamNo(ParamNo), Callee(Callee), Offsets(Offsets) {}
  545. };
  546. uint64_t ParamNo = 0;
  547. /// The range contains byte offsets from the parameter pointer which
  548. /// accessed by the function. In the per-module summary, it only includes
  549. /// accesses made by the function instructions. In the combined summary, it
  550. /// also includes accesses by nested function calls.
  551. ConstantRange Use{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
  552. /// In the per-module summary, it summarizes the byte offset applied to each
  553. /// pointer parameter before passing to each corresponding callee.
  554. /// In the combined summary, it's empty and information is propagated by
  555. /// inter-procedural analysis and applied to the Use field.
  556. std::vector<Call> Calls;
  557. ParamAccess() = default;
  558. ParamAccess(uint64_t ParamNo, const ConstantRange &Use)
  559. : ParamNo(ParamNo), Use(Use) {}
  560. };
  561. /// Create an empty FunctionSummary (with specified call edges).
  562. /// Used to represent external nodes and the dummy root node.
  563. static FunctionSummary
  564. makeDummyFunctionSummary(std::vector<FunctionSummary::EdgeTy> Edges) {
  565. return FunctionSummary(
  566. FunctionSummary::GVFlags(
  567. GlobalValue::LinkageTypes::AvailableExternallyLinkage,
  568. GlobalValue::DefaultVisibility,
  569. /*NotEligibleToImport=*/true, /*Live=*/true, /*IsLocal=*/false,
  570. /*CanAutoHide=*/false),
  571. /*NumInsts=*/0, FunctionSummary::FFlags{}, /*EntryCount=*/0,
  572. std::vector<ValueInfo>(), std::move(Edges),
  573. std::vector<GlobalValue::GUID>(),
  574. std::vector<FunctionSummary::VFuncId>(),
  575. std::vector<FunctionSummary::VFuncId>(),
  576. std::vector<FunctionSummary::ConstVCall>(),
  577. std::vector<FunctionSummary::ConstVCall>(),
  578. std::vector<FunctionSummary::ParamAccess>());
  579. }
  580. /// A dummy node to reference external functions that aren't in the index
  581. static FunctionSummary ExternalNode;
  582. private:
  583. /// Number of instructions (ignoring debug instructions, e.g.) computed
  584. /// during the initial compile step when the summary index is first built.
  585. unsigned InstCount;
  586. /// Function summary specific flags.
  587. FFlags FunFlags;
  588. /// The synthesized entry count of the function.
  589. /// This is only populated during ThinLink phase and remains unused while
  590. /// generating per-module summaries.
  591. uint64_t EntryCount = 0;
  592. /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
  593. std::vector<EdgeTy> CallGraphEdgeList;
  594. std::unique_ptr<TypeIdInfo> TIdInfo;
  595. /// Uses for every parameter to this function.
  596. using ParamAccessesTy = std::vector<ParamAccess>;
  597. std::unique_ptr<ParamAccessesTy> ParamAccesses;
  598. public:
  599. FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags,
  600. uint64_t EntryCount, std::vector<ValueInfo> Refs,
  601. std::vector<EdgeTy> CGEdges,
  602. std::vector<GlobalValue::GUID> TypeTests,
  603. std::vector<VFuncId> TypeTestAssumeVCalls,
  604. std::vector<VFuncId> TypeCheckedLoadVCalls,
  605. std::vector<ConstVCall> TypeTestAssumeConstVCalls,
  606. std::vector<ConstVCall> TypeCheckedLoadConstVCalls,
  607. std::vector<ParamAccess> Params)
  608. : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
  609. InstCount(NumInsts), FunFlags(FunFlags), EntryCount(EntryCount),
  610. CallGraphEdgeList(std::move(CGEdges)) {
  611. if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
  612. !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
  613. !TypeCheckedLoadConstVCalls.empty())
  614. TIdInfo = std::make_unique<TypeIdInfo>(
  615. TypeIdInfo{std::move(TypeTests), std::move(TypeTestAssumeVCalls),
  616. std::move(TypeCheckedLoadVCalls),
  617. std::move(TypeTestAssumeConstVCalls),
  618. std::move(TypeCheckedLoadConstVCalls)});
  619. if (!Params.empty())
  620. ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(Params));
  621. }
  622. // Gets the number of readonly and writeonly refs in RefEdgeList
  623. std::pair<unsigned, unsigned> specialRefCounts() const;
  624. /// Check if this is a function summary.
  625. static bool classof(const GlobalValueSummary *GVS) {
  626. return GVS->getSummaryKind() == FunctionKind;
  627. }
  628. /// Get function summary flags.
  629. FFlags fflags() const { return FunFlags; }
  630. void setNoRecurse() { FunFlags.NoRecurse = true; }
  631. void setNoUnwind() { FunFlags.NoUnwind = true; }
  632. /// Get the instruction count recorded for this function.
  633. unsigned instCount() const { return InstCount; }
  634. /// Get the synthetic entry count for this function.
  635. uint64_t entryCount() const { return EntryCount; }
  636. /// Set the synthetic entry count for this function.
  637. void setEntryCount(uint64_t EC) { EntryCount = EC; }
  638. /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
  639. ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
  640. std::vector<EdgeTy> &mutableCalls() { return CallGraphEdgeList; }
  641. void addCall(EdgeTy E) { CallGraphEdgeList.push_back(E); }
  642. /// Returns the list of type identifiers used by this function in
  643. /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
  644. /// represented as GUIDs.
  645. ArrayRef<GlobalValue::GUID> type_tests() const {
  646. if (TIdInfo)
  647. return TIdInfo->TypeTests;
  648. return {};
  649. }
  650. /// Returns the list of virtual calls made by this function using
  651. /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
  652. /// integer arguments.
  653. ArrayRef<VFuncId> type_test_assume_vcalls() const {
  654. if (TIdInfo)
  655. return TIdInfo->TypeTestAssumeVCalls;
  656. return {};
  657. }
  658. /// Returns the list of virtual calls made by this function using
  659. /// llvm.type.checked.load intrinsics that do not have all constant integer
  660. /// arguments.
  661. ArrayRef<VFuncId> type_checked_load_vcalls() const {
  662. if (TIdInfo)
  663. return TIdInfo->TypeCheckedLoadVCalls;
  664. return {};
  665. }
  666. /// Returns the list of virtual calls made by this function using
  667. /// llvm.assume(llvm.type.test) intrinsics with all constant integer
  668. /// arguments.
  669. ArrayRef<ConstVCall> type_test_assume_const_vcalls() const {
  670. if (TIdInfo)
  671. return TIdInfo->TypeTestAssumeConstVCalls;
  672. return {};
  673. }
  674. /// Returns the list of virtual calls made by this function using
  675. /// llvm.type.checked.load intrinsics with all constant integer arguments.
  676. ArrayRef<ConstVCall> type_checked_load_const_vcalls() const {
  677. if (TIdInfo)
  678. return TIdInfo->TypeCheckedLoadConstVCalls;
  679. return {};
  680. }
  681. /// Returns the list of known uses of pointer parameters.
  682. ArrayRef<ParamAccess> paramAccesses() const {
  683. if (ParamAccesses)
  684. return *ParamAccesses;
  685. return {};
  686. }
  687. /// Sets the list of known uses of pointer parameters.
  688. void setParamAccesses(std::vector<ParamAccess> NewParams) {
  689. if (NewParams.empty())
  690. ParamAccesses.reset();
  691. else if (ParamAccesses)
  692. *ParamAccesses = std::move(NewParams);
  693. else
  694. ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(NewParams));
  695. }
  696. /// Add a type test to the summary. This is used by WholeProgramDevirt if we
  697. /// were unable to devirtualize a checked call.
  698. void addTypeTest(GlobalValue::GUID Guid) {
  699. if (!TIdInfo)
  700. TIdInfo = std::make_unique<TypeIdInfo>();
  701. TIdInfo->TypeTests.push_back(Guid);
  702. }
  703. const TypeIdInfo *getTypeIdInfo() const { return TIdInfo.get(); };
  704. friend struct GraphTraits<ValueInfo>;
  705. };
  706. template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
  707. static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
  708. static FunctionSummary::VFuncId getTombstoneKey() {
  709. return {0, uint64_t(-2)};
  710. }
  711. static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R) {
  712. return L.GUID == R.GUID && L.Offset == R.Offset;
  713. }
  714. static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
  715. };
  716. template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
  717. static FunctionSummary::ConstVCall getEmptyKey() {
  718. return {{0, uint64_t(-1)}, {}};
  719. }
  720. static FunctionSummary::ConstVCall getTombstoneKey() {
  721. return {{0, uint64_t(-2)}, {}};
  722. }
  723. static bool isEqual(FunctionSummary::ConstVCall L,
  724. FunctionSummary::ConstVCall R) {
  725. return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
  726. L.Args == R.Args;
  727. }
  728. static unsigned getHashValue(FunctionSummary::ConstVCall I) {
  729. return I.VFunc.GUID;
  730. }
  731. };
  732. /// The ValueInfo and offset for a function within a vtable definition
  733. /// initializer array.
  734. struct VirtFuncOffset {
  735. VirtFuncOffset(ValueInfo VI, uint64_t Offset)
  736. : FuncVI(VI), VTableOffset(Offset) {}
  737. ValueInfo FuncVI;
  738. uint64_t VTableOffset;
  739. };
  740. /// List of functions referenced by a particular vtable definition.
  741. using VTableFuncList = std::vector<VirtFuncOffset>;
  742. /// Global variable summary information to aid decisions and
  743. /// implementation of importing.
  744. ///
  745. /// Global variable summary has two extra flag, telling if it is
  746. /// readonly or writeonly. Both readonly and writeonly variables
  747. /// can be optimized in the backed: readonly variables can be
  748. /// const-folded, while writeonly vars can be completely eliminated
  749. /// together with corresponding stores. We let both things happen
  750. /// by means of internalizing such variables after ThinLTO import.
  751. class GlobalVarSummary : public GlobalValueSummary {
  752. private:
  753. /// For vtable definitions this holds the list of functions and
  754. /// their corresponding offsets within the initializer array.
  755. std::unique_ptr<VTableFuncList> VTableFuncs;
  756. public:
  757. struct GVarFlags {
  758. GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant,
  759. GlobalObject::VCallVisibility Vis)
  760. : MaybeReadOnly(ReadOnly), MaybeWriteOnly(WriteOnly),
  761. Constant(Constant), VCallVisibility(Vis) {}
  762. // If true indicates that this global variable might be accessed
  763. // purely by non-volatile load instructions. This in turn means
  764. // it can be internalized in source and destination modules during
  765. // thin LTO import because it neither modified nor its address
  766. // is taken.
  767. unsigned MaybeReadOnly : 1;
  768. // If true indicates that variable is possibly only written to, so
  769. // its value isn't loaded and its address isn't taken anywhere.
  770. // False, when 'Constant' attribute is set.
  771. unsigned MaybeWriteOnly : 1;
  772. // Indicates that value is a compile-time constant. Global variable
  773. // can be 'Constant' while not being 'ReadOnly' on several occasions:
  774. // - it is volatile, (e.g mapped device address)
  775. // - its address is taken, meaning that unlike 'ReadOnly' vars we can't
  776. // internalize it.
  777. // Constant variables are always imported thus giving compiler an
  778. // opportunity to make some extra optimizations. Readonly constants
  779. // are also internalized.
  780. unsigned Constant : 1;
  781. // Set from metadata on vtable definitions during the module summary
  782. // analysis.
  783. unsigned VCallVisibility : 2;
  784. } VarFlags;
  785. GlobalVarSummary(GVFlags Flags, GVarFlags VarFlags,
  786. std::vector<ValueInfo> Refs)
  787. : GlobalValueSummary(GlobalVarKind, Flags, std::move(Refs)),
  788. VarFlags(VarFlags) {}
  789. /// Check if this is a global variable summary.
  790. static bool classof(const GlobalValueSummary *GVS) {
  791. return GVS->getSummaryKind() == GlobalVarKind;
  792. }
  793. GVarFlags varflags() const { return VarFlags; }
  794. void setReadOnly(bool RO) { VarFlags.MaybeReadOnly = RO; }
  795. void setWriteOnly(bool WO) { VarFlags.MaybeWriteOnly = WO; }
  796. bool maybeReadOnly() const { return VarFlags.MaybeReadOnly; }
  797. bool maybeWriteOnly() const { return VarFlags.MaybeWriteOnly; }
  798. bool isConstant() const { return VarFlags.Constant; }
  799. void setVCallVisibility(GlobalObject::VCallVisibility Vis) {
  800. VarFlags.VCallVisibility = Vis;
  801. }
  802. GlobalObject::VCallVisibility getVCallVisibility() const {
  803. return (GlobalObject::VCallVisibility)VarFlags.VCallVisibility;
  804. }
  805. void setVTableFuncs(VTableFuncList Funcs) {
  806. assert(!VTableFuncs);
  807. VTableFuncs = std::make_unique<VTableFuncList>(std::move(Funcs));
  808. }
  809. ArrayRef<VirtFuncOffset> vTableFuncs() const {
  810. if (VTableFuncs)
  811. return *VTableFuncs;
  812. return {};
  813. }
  814. };
  815. struct TypeTestResolution {
  816. /// Specifies which kind of type check we should emit for this byte array.
  817. /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
  818. /// details on each kind of check; the enumerators are described with
  819. /// reference to that document.
  820. enum Kind {
  821. Unsat, ///< Unsatisfiable type (i.e. no global has this type metadata)
  822. ByteArray, ///< Test a byte array (first example)
  823. Inline, ///< Inlined bit vector ("Short Inline Bit Vectors")
  824. Single, ///< Single element (last example in "Short Inline Bit Vectors")
  825. AllOnes, ///< All-ones bit vector ("Eliminating Bit Vector Checks for
  826. /// All-Ones Bit Vectors")
  827. Unknown, ///< Unknown (analysis not performed, don't lower)
  828. } TheKind = Unknown;
  829. /// Range of size-1 expressed as a bit width. For example, if the size is in
  830. /// range [1,256], this number will be 8. This helps generate the most compact
  831. /// instruction sequences.
  832. unsigned SizeM1BitWidth = 0;
  833. // The following fields are only used if the target does not support the use
  834. // of absolute symbols to store constants. Their meanings are the same as the
  835. // corresponding fields in LowerTypeTestsModule::TypeIdLowering in
  836. // LowerTypeTests.cpp.
  837. uint64_t AlignLog2 = 0;
  838. uint64_t SizeM1 = 0;
  839. uint8_t BitMask = 0;
  840. uint64_t InlineBits = 0;
  841. };
  842. struct WholeProgramDevirtResolution {
  843. enum Kind {
  844. Indir, ///< Just do a regular virtual call
  845. SingleImpl, ///< Single implementation devirtualization
  846. BranchFunnel, ///< When retpoline mitigation is enabled, use a branch funnel
  847. ///< that is defined in the merged module. Otherwise same as
  848. ///< Indir.
  849. } TheKind = Indir;
  850. std::string SingleImplName;
  851. struct ByArg {
  852. enum Kind {
  853. Indir, ///< Just do a regular virtual call
  854. UniformRetVal, ///< Uniform return value optimization
  855. UniqueRetVal, ///< Unique return value optimization
  856. VirtualConstProp, ///< Virtual constant propagation
  857. } TheKind = Indir;
  858. /// Additional information for the resolution:
  859. /// - UniformRetVal: the uniform return value.
  860. /// - UniqueRetVal: the return value associated with the unique vtable (0 or
  861. /// 1).
  862. uint64_t Info = 0;
  863. // The following fields are only used if the target does not support the use
  864. // of absolute symbols to store constants.
  865. uint32_t Byte = 0;
  866. uint32_t Bit = 0;
  867. };
  868. /// Resolutions for calls with all constant integer arguments (excluding the
  869. /// first argument, "this"), where the key is the argument vector.
  870. std::map<std::vector<uint64_t>, ByArg> ResByArg;
  871. };
  872. struct TypeIdSummary {
  873. TypeTestResolution TTRes;
  874. /// Mapping from byte offset to whole-program devirt resolution for that
  875. /// (typeid, byte offset) pair.
  876. std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
  877. };
  878. /// 160 bits SHA1
  879. using ModuleHash = std::array<uint32_t, 5>;
  880. /// Type used for iterating through the global value summary map.
  881. using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator;
  882. using gvsummary_iterator = GlobalValueSummaryMapTy::iterator;
  883. /// String table to hold/own module path strings, which additionally holds the
  884. /// module ID assigned to each module during the plugin step, as well as a hash
  885. /// of the module. The StringMap makes a copy of and owns inserted strings.
  886. using ModulePathStringTableTy = StringMap<std::pair<uint64_t, ModuleHash>>;
  887. /// Map of global value GUID to its summary, used to identify values defined in
  888. /// a particular module, and provide efficient access to their summary.
  889. using GVSummaryMapTy = DenseMap<GlobalValue::GUID, GlobalValueSummary *>;
  890. /// Map of a type GUID to type id string and summary (multimap used
  891. /// in case of GUID conflicts).
  892. using TypeIdSummaryMapTy =
  893. std::multimap<GlobalValue::GUID, std::pair<std::string, TypeIdSummary>>;
  894. /// The following data structures summarize type metadata information.
  895. /// For type metadata overview see https://llvm.org/docs/TypeMetadata.html.
  896. /// Each type metadata includes both the type identifier and the offset of
  897. /// the address point of the type (the address held by objects of that type
  898. /// which may not be the beginning of the virtual table). Vtable definitions
  899. /// are decorated with type metadata for the types they are compatible with.
  900. ///
  901. /// Holds information about vtable definitions decorated with type metadata:
  902. /// the vtable definition value and its address point offset in a type
  903. /// identifier metadata it is decorated (compatible) with.
  904. struct TypeIdOffsetVtableInfo {
  905. TypeIdOffsetVtableInfo(uint64_t Offset, ValueInfo VI)
  906. : AddressPointOffset(Offset), VTableVI(VI) {}
  907. uint64_t AddressPointOffset;
  908. ValueInfo VTableVI;
  909. };
  910. /// List of vtable definitions decorated by a particular type identifier,
  911. /// and their corresponding offsets in that type identifier's metadata.
  912. /// Note that each type identifier may be compatible with multiple vtables, due
  913. /// to inheritance, which is why this is a vector.
  914. using TypeIdCompatibleVtableInfo = std::vector<TypeIdOffsetVtableInfo>;
  915. /// Class to hold module path string table and global value map,
  916. /// and encapsulate methods for operating on them.
  917. class ModuleSummaryIndex {
  918. private:
  919. /// Map from value name to list of summary instances for values of that
  920. /// name (may be duplicates in the COMDAT case, e.g.).
  921. GlobalValueSummaryMapTy GlobalValueMap;
  922. /// Holds strings for combined index, mapping to the corresponding module ID.
  923. ModulePathStringTableTy ModulePathStringTable;
  924. /// Mapping from type identifier GUIDs to type identifier and its summary
  925. /// information. Produced by thin link.
  926. TypeIdSummaryMapTy TypeIdMap;
  927. /// Mapping from type identifier to information about vtables decorated
  928. /// with that type identifier's metadata. Produced by per module summary
  929. /// analysis and consumed by thin link. For more information, see description
  930. /// above where TypeIdCompatibleVtableInfo is defined.
  931. std::map<std::string, TypeIdCompatibleVtableInfo, std::less<>>
  932. TypeIdCompatibleVtableMap;
  933. /// Mapping from original ID to GUID. If original ID can map to multiple
  934. /// GUIDs, it will be mapped to 0.
  935. std::map<GlobalValue::GUID, GlobalValue::GUID> OidGuidMap;
  936. /// Indicates that summary-based GlobalValue GC has run, and values with
  937. /// GVFlags::Live==false are really dead. Otherwise, all values must be
  938. /// considered live.
  939. bool WithGlobalValueDeadStripping = false;
  940. /// Indicates that summary-based attribute propagation has run and
  941. /// GVarFlags::MaybeReadonly / GVarFlags::MaybeWriteonly are really
  942. /// read/write only.
  943. bool WithAttributePropagation = false;
  944. /// Indicates that summary-based DSOLocal propagation has run and the flag in
  945. /// every summary of a GV is synchronized.
  946. bool WithDSOLocalPropagation = false;
  947. /// Indicates that summary-based synthetic entry count propagation has run
  948. bool HasSyntheticEntryCounts = false;
  949. /// Indicates that distributed backend should skip compilation of the
  950. /// module. Flag is suppose to be set by distributed ThinLTO indexing
  951. /// when it detected that the module is not needed during the final
  952. /// linking. As result distributed backend should just output a minimal
  953. /// valid object file.
  954. bool SkipModuleByDistributedBackend = false;
  955. /// If true then we're performing analysis of IR module, or parsing along with
  956. /// the IR from assembly. The value of 'false' means we're reading summary
  957. /// from BC or YAML source. Affects the type of value stored in NameOrGV
  958. /// union.
  959. bool HaveGVs;
  960. // True if the index was created for a module compiled with -fsplit-lto-unit.
  961. bool EnableSplitLTOUnit;
  962. // True if some of the modules were compiled with -fsplit-lto-unit and
  963. // some were not. Set when the combined index is created during the thin link.
  964. bool PartiallySplitLTOUnits = false;
  965. /// True if some of the FunctionSummary contains a ParamAccess.
  966. bool HasParamAccess = false;
  967. std::set<std::string> CfiFunctionDefs;
  968. std::set<std::string> CfiFunctionDecls;
  969. // Used in cases where we want to record the name of a global, but
  970. // don't have the string owned elsewhere (e.g. the Strtab on a module).
  971. StringSaver Saver;
  972. BumpPtrAllocator Alloc;
  973. // The total number of basic blocks in the module in the per-module summary or
  974. // the total number of basic blocks in the LTO unit in the combined index.
  975. uint64_t BlockCount;
  976. // YAML I/O support.
  977. friend yaml::MappingTraits<ModuleSummaryIndex>;
  978. GlobalValueSummaryMapTy::value_type *
  979. getOrInsertValuePtr(GlobalValue::GUID GUID) {
  980. return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo(HaveGVs))
  981. .first;
  982. }
  983. public:
  984. // See HaveGVs variable comment.
  985. ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit = false)
  986. : HaveGVs(HaveGVs), EnableSplitLTOUnit(EnableSplitLTOUnit), Saver(Alloc),
  987. BlockCount(0) {}
  988. // Current version for the module summary in bitcode files.
  989. // The BitcodeSummaryVersion should be bumped whenever we introduce changes
  990. // in the way some record are interpreted, like flags for instance.
  991. // Note that incrementing this may require changes in both BitcodeReader.cpp
  992. // and BitcodeWriter.cpp.
  993. static constexpr uint64_t BitcodeSummaryVersion = 9;
  994. // Regular LTO module name for ASM writer
  995. static constexpr const char *getRegularLTOModuleName() {
  996. return "[Regular LTO]";
  997. }
  998. bool haveGVs() const { return HaveGVs; }
  999. uint64_t getFlags() const;
  1000. void setFlags(uint64_t Flags);
  1001. uint64_t getBlockCount() const { return BlockCount; }
  1002. void addBlockCount(uint64_t C) { BlockCount += C; }
  1003. void setBlockCount(uint64_t C) { BlockCount = C; }
  1004. gvsummary_iterator begin() { return GlobalValueMap.begin(); }
  1005. const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
  1006. gvsummary_iterator end() { return GlobalValueMap.end(); }
  1007. const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
  1008. size_t size() const { return GlobalValueMap.size(); }
  1009. /// Convenience function for doing a DFS on a ValueInfo. Marks the function in
  1010. /// the FunctionHasParent map.
  1011. static void discoverNodes(ValueInfo V,
  1012. std::map<ValueInfo, bool> &FunctionHasParent) {
  1013. if (!V.getSummaryList().size())
  1014. return; // skip external functions that don't have summaries
  1015. // Mark discovered if we haven't yet
  1016. auto S = FunctionHasParent.emplace(V, false);
  1017. // Stop if we've already discovered this node
  1018. if (!S.second)
  1019. return;
  1020. FunctionSummary *F =
  1021. dyn_cast<FunctionSummary>(V.getSummaryList().front().get());
  1022. assert(F != nullptr && "Expected FunctionSummary node");
  1023. for (auto &C : F->calls()) {
  1024. // Insert node if necessary
  1025. auto S = FunctionHasParent.emplace(C.first, true);
  1026. // Skip nodes that we're sure have parents
  1027. if (!S.second && S.first->second)
  1028. continue;
  1029. if (S.second)
  1030. discoverNodes(C.first, FunctionHasParent);
  1031. else
  1032. S.first->second = true;
  1033. }
  1034. }
  1035. // Calculate the callgraph root
  1036. FunctionSummary calculateCallGraphRoot() {
  1037. // Functions that have a parent will be marked in FunctionHasParent pair.
  1038. // Once we've marked all functions, the functions in the map that are false
  1039. // have no parent (so they're the roots)
  1040. std::map<ValueInfo, bool> FunctionHasParent;
  1041. for (auto &S : *this) {
  1042. // Skip external functions
  1043. if (!S.second.SummaryList.size() ||
  1044. !isa<FunctionSummary>(S.second.SummaryList.front().get()))
  1045. continue;
  1046. discoverNodes(ValueInfo(HaveGVs, &S), FunctionHasParent);
  1047. }
  1048. std::vector<FunctionSummary::EdgeTy> Edges;
  1049. // create edges to all roots in the Index
  1050. for (auto &P : FunctionHasParent) {
  1051. if (P.second)
  1052. continue; // skip over non-root nodes
  1053. Edges.push_back(std::make_pair(P.first, CalleeInfo{}));
  1054. }
  1055. if (Edges.empty()) {
  1056. // Failed to find root - return an empty node
  1057. return FunctionSummary::makeDummyFunctionSummary({});
  1058. }
  1059. auto CallGraphRoot = FunctionSummary::makeDummyFunctionSummary(Edges);
  1060. return CallGraphRoot;
  1061. }
  1062. bool withGlobalValueDeadStripping() const {
  1063. return WithGlobalValueDeadStripping;
  1064. }
  1065. void setWithGlobalValueDeadStripping() {
  1066. WithGlobalValueDeadStripping = true;
  1067. }
  1068. bool withAttributePropagation() const { return WithAttributePropagation; }
  1069. void setWithAttributePropagation() {
  1070. WithAttributePropagation = true;
  1071. }
  1072. bool withDSOLocalPropagation() const { return WithDSOLocalPropagation; }
  1073. void setWithDSOLocalPropagation() { WithDSOLocalPropagation = true; }
  1074. bool isReadOnly(const GlobalVarSummary *GVS) const {
  1075. return WithAttributePropagation && GVS->maybeReadOnly();
  1076. }
  1077. bool isWriteOnly(const GlobalVarSummary *GVS) const {
  1078. return WithAttributePropagation && GVS->maybeWriteOnly();
  1079. }
  1080. bool hasSyntheticEntryCounts() const { return HasSyntheticEntryCounts; }
  1081. void setHasSyntheticEntryCounts() { HasSyntheticEntryCounts = true; }
  1082. bool skipModuleByDistributedBackend() const {
  1083. return SkipModuleByDistributedBackend;
  1084. }
  1085. void setSkipModuleByDistributedBackend() {
  1086. SkipModuleByDistributedBackend = true;
  1087. }
  1088. bool enableSplitLTOUnit() const { return EnableSplitLTOUnit; }
  1089. void setEnableSplitLTOUnit() { EnableSplitLTOUnit = true; }
  1090. bool partiallySplitLTOUnits() const { return PartiallySplitLTOUnits; }
  1091. void setPartiallySplitLTOUnits() { PartiallySplitLTOUnits = true; }
  1092. bool hasParamAccess() const { return HasParamAccess; }
  1093. bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
  1094. return !WithGlobalValueDeadStripping || GVS->isLive();
  1095. }
  1096. bool isGUIDLive(GlobalValue::GUID GUID) const;
  1097. /// Return a ValueInfo for the index value_type (convenient when iterating
  1098. /// index).
  1099. ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const {
  1100. return ValueInfo(HaveGVs, &R);
  1101. }
  1102. /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
  1103. ValueInfo getValueInfo(GlobalValue::GUID GUID) const {
  1104. auto I = GlobalValueMap.find(GUID);
  1105. return ValueInfo(HaveGVs, I == GlobalValueMap.end() ? nullptr : &*I);
  1106. }
  1107. /// Return a ValueInfo for \p GUID.
  1108. ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID) {
  1109. return ValueInfo(HaveGVs, getOrInsertValuePtr(GUID));
  1110. }
  1111. // Save a string in the Index. Use before passing Name to
  1112. // getOrInsertValueInfo when the string isn't owned elsewhere (e.g. on the
  1113. // module's Strtab).
  1114. StringRef saveString(StringRef String) { return Saver.save(String); }
  1115. /// Return a ValueInfo for \p GUID setting value \p Name.
  1116. ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID, StringRef Name) {
  1117. assert(!HaveGVs);
  1118. auto VP = getOrInsertValuePtr(GUID);
  1119. VP->second.U.Name = Name;
  1120. return ValueInfo(HaveGVs, VP);
  1121. }
  1122. /// Return a ValueInfo for \p GV and mark it as belonging to GV.
  1123. ValueInfo getOrInsertValueInfo(const GlobalValue *GV) {
  1124. assert(HaveGVs);
  1125. auto VP = getOrInsertValuePtr(GV->getGUID());
  1126. VP->second.U.GV = GV;
  1127. return ValueInfo(HaveGVs, VP);
  1128. }
  1129. /// Return the GUID for \p OriginalId in the OidGuidMap.
  1130. GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const {
  1131. const auto I = OidGuidMap.find(OriginalID);
  1132. return I == OidGuidMap.end() ? 0 : I->second;
  1133. }
  1134. std::set<std::string> &cfiFunctionDefs() { return CfiFunctionDefs; }
  1135. const std::set<std::string> &cfiFunctionDefs() const { return CfiFunctionDefs; }
  1136. std::set<std::string> &cfiFunctionDecls() { return CfiFunctionDecls; }
  1137. const std::set<std::string> &cfiFunctionDecls() const { return CfiFunctionDecls; }
  1138. /// Add a global value summary for a value.
  1139. void addGlobalValueSummary(const GlobalValue &GV,
  1140. std::unique_ptr<GlobalValueSummary> Summary) {
  1141. addGlobalValueSummary(getOrInsertValueInfo(&GV), std::move(Summary));
  1142. }
  1143. /// Add a global value summary for a value of the given name.
  1144. void addGlobalValueSummary(StringRef ValueName,
  1145. std::unique_ptr<GlobalValueSummary> Summary) {
  1146. addGlobalValueSummary(getOrInsertValueInfo(GlobalValue::getGUID(ValueName)),
  1147. std::move(Summary));
  1148. }
  1149. /// Add a global value summary for the given ValueInfo.
  1150. void addGlobalValueSummary(ValueInfo VI,
  1151. std::unique_ptr<GlobalValueSummary> Summary) {
  1152. if (const FunctionSummary *FS = dyn_cast<FunctionSummary>(Summary.get()))
  1153. HasParamAccess |= !FS->paramAccesses().empty();
  1154. addOriginalName(VI.getGUID(), Summary->getOriginalName());
  1155. // Here we have a notionally const VI, but the value it points to is owned
  1156. // by the non-const *this.
  1157. const_cast<GlobalValueSummaryMapTy::value_type *>(VI.getRef())
  1158. ->second.SummaryList.push_back(std::move(Summary));
  1159. }
  1160. /// Add an original name for the value of the given GUID.
  1161. void addOriginalName(GlobalValue::GUID ValueGUID,
  1162. GlobalValue::GUID OrigGUID) {
  1163. if (OrigGUID == 0 || ValueGUID == OrigGUID)
  1164. return;
  1165. if (OidGuidMap.count(OrigGUID) && OidGuidMap[OrigGUID] != ValueGUID)
  1166. OidGuidMap[OrigGUID] = 0;
  1167. else
  1168. OidGuidMap[OrigGUID] = ValueGUID;
  1169. }
  1170. /// Find the summary for ValueInfo \p VI in module \p ModuleId, or nullptr if
  1171. /// not found.
  1172. GlobalValueSummary *findSummaryInModule(ValueInfo VI, StringRef ModuleId) const {
  1173. auto SummaryList = VI.getSummaryList();
  1174. auto Summary =
  1175. llvm::find_if(SummaryList,
  1176. [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
  1177. return Summary->modulePath() == ModuleId;
  1178. });
  1179. if (Summary == SummaryList.end())
  1180. return nullptr;
  1181. return Summary->get();
  1182. }
  1183. /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
  1184. /// not found.
  1185. GlobalValueSummary *findSummaryInModule(GlobalValue::GUID ValueGUID,
  1186. StringRef ModuleId) const {
  1187. auto CalleeInfo = getValueInfo(ValueGUID);
  1188. if (!CalleeInfo)
  1189. return nullptr; // This function does not have a summary
  1190. return findSummaryInModule(CalleeInfo, ModuleId);
  1191. }
  1192. /// Returns the first GlobalValueSummary for \p GV, asserting that there
  1193. /// is only one if \p PerModuleIndex.
  1194. GlobalValueSummary *getGlobalValueSummary(const GlobalValue &GV,
  1195. bool PerModuleIndex = true) const {
  1196. assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
  1197. return getGlobalValueSummary(GV.getGUID(), PerModuleIndex);
  1198. }
  1199. /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
  1200. /// there
  1201. /// is only one if \p PerModuleIndex.
  1202. GlobalValueSummary *getGlobalValueSummary(GlobalValue::GUID ValueGUID,
  1203. bool PerModuleIndex = true) const;
  1204. /// Table of modules, containing module hash and id.
  1205. const StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() const {
  1206. return ModulePathStringTable;
  1207. }
  1208. /// Table of modules, containing hash and id.
  1209. StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() {
  1210. return ModulePathStringTable;
  1211. }
  1212. /// Get the module ID recorded for the given module path.
  1213. uint64_t getModuleId(const StringRef ModPath) const {
  1214. return ModulePathStringTable.lookup(ModPath).first;
  1215. }
  1216. /// Get the module SHA1 hash recorded for the given module path.
  1217. const ModuleHash &getModuleHash(const StringRef ModPath) const {
  1218. auto It = ModulePathStringTable.find(ModPath);
  1219. assert(It != ModulePathStringTable.end() && "Module not registered");
  1220. return It->second.second;
  1221. }
  1222. /// Convenience method for creating a promoted global name
  1223. /// for the given value name of a local, and its original module's ID.
  1224. static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
  1225. SmallString<256> NewName(Name);
  1226. NewName += ".llvm.";
  1227. NewName += utostr((uint64_t(ModHash[0]) << 32) |
  1228. ModHash[1]); // Take the first 64 bits
  1229. return std::string(NewName.str());
  1230. }
  1231. /// Helper to obtain the unpromoted name for a global value (or the original
  1232. /// name if not promoted). Split off the rightmost ".llvm.${hash}" suffix,
  1233. /// because it is possible in certain clients (not clang at the moment) for
  1234. /// two rounds of ThinLTO optimization and therefore promotion to occur.
  1235. static StringRef getOriginalNameBeforePromote(StringRef Name) {
  1236. std::pair<StringRef, StringRef> Pair = Name.rsplit(".llvm.");
  1237. return Pair.first;
  1238. }
  1239. typedef ModulePathStringTableTy::value_type ModuleInfo;
  1240. /// Add a new module with the given \p Hash, mapped to the given \p
  1241. /// ModID, and return a reference to the module.
  1242. ModuleInfo *addModule(StringRef ModPath, uint64_t ModId,
  1243. ModuleHash Hash = ModuleHash{{0}}) {
  1244. return &*ModulePathStringTable.insert({ModPath, {ModId, Hash}}).first;
  1245. }
  1246. /// Return module entry for module with the given \p ModPath.
  1247. ModuleInfo *getModule(StringRef ModPath) {
  1248. auto It = ModulePathStringTable.find(ModPath);
  1249. assert(It != ModulePathStringTable.end() && "Module not registered");
  1250. return &*It;
  1251. }
  1252. /// Check if the given Module has any functions available for exporting
  1253. /// in the index. We consider any module present in the ModulePathStringTable
  1254. /// to have exported functions.
  1255. bool hasExportedFunctions(const Module &M) const {
  1256. return ModulePathStringTable.count(M.getModuleIdentifier());
  1257. }
  1258. const TypeIdSummaryMapTy &typeIds() const { return TypeIdMap; }
  1259. /// Return an existing or new TypeIdSummary entry for \p TypeId.
  1260. /// This accessor can mutate the map and therefore should not be used in
  1261. /// the ThinLTO backends.
  1262. TypeIdSummary &getOrInsertTypeIdSummary(StringRef TypeId) {
  1263. auto TidIter = TypeIdMap.equal_range(GlobalValue::getGUID(TypeId));
  1264. for (auto It = TidIter.first; It != TidIter.second; ++It)
  1265. if (It->second.first == TypeId)
  1266. return It->second.second;
  1267. auto It = TypeIdMap.insert(
  1268. {GlobalValue::getGUID(TypeId), {std::string(TypeId), TypeIdSummary()}});
  1269. return It->second.second;
  1270. }
  1271. /// This returns either a pointer to the type id summary (if present in the
  1272. /// summary map) or null (if not present). This may be used when importing.
  1273. const TypeIdSummary *getTypeIdSummary(StringRef TypeId) const {
  1274. auto TidIter = TypeIdMap.equal_range(GlobalValue::getGUID(TypeId));
  1275. for (auto It = TidIter.first; It != TidIter.second; ++It)
  1276. if (It->second.first == TypeId)
  1277. return &It->second.second;
  1278. return nullptr;
  1279. }
  1280. TypeIdSummary *getTypeIdSummary(StringRef TypeId) {
  1281. return const_cast<TypeIdSummary *>(
  1282. static_cast<const ModuleSummaryIndex *>(this)->getTypeIdSummary(
  1283. TypeId));
  1284. }
  1285. const auto &typeIdCompatibleVtableMap() const {
  1286. return TypeIdCompatibleVtableMap;
  1287. }
  1288. /// Return an existing or new TypeIdCompatibleVtableMap entry for \p TypeId.
  1289. /// This accessor can mutate the map and therefore should not be used in
  1290. /// the ThinLTO backends.
  1291. TypeIdCompatibleVtableInfo &
  1292. getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId) {
  1293. return TypeIdCompatibleVtableMap[std::string(TypeId)];
  1294. }
  1295. /// For the given \p TypeId, this returns the TypeIdCompatibleVtableMap
  1296. /// entry if present in the summary map. This may be used when importing.
  1297. Optional<TypeIdCompatibleVtableInfo>
  1298. getTypeIdCompatibleVtableSummary(StringRef TypeId) const {
  1299. auto I = TypeIdCompatibleVtableMap.find(TypeId);
  1300. if (I == TypeIdCompatibleVtableMap.end())
  1301. return None;
  1302. return I->second;
  1303. }
  1304. /// Collect for the given module the list of functions it defines
  1305. /// (GUID -> Summary).
  1306. void collectDefinedFunctionsForModule(StringRef ModulePath,
  1307. GVSummaryMapTy &GVSummaryMap) const;
  1308. /// Collect for each module the list of Summaries it defines (GUID ->
  1309. /// Summary).
  1310. template <class Map>
  1311. void
  1312. collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const {
  1313. for (auto &GlobalList : *this) {
  1314. auto GUID = GlobalList.first;
  1315. for (auto &Summary : GlobalList.second.SummaryList) {
  1316. ModuleToDefinedGVSummaries[Summary->modulePath()][GUID] = Summary.get();
  1317. }
  1318. }
  1319. }
  1320. /// Print to an output stream.
  1321. void print(raw_ostream &OS, bool IsForDebug = false) const;
  1322. /// Dump to stderr (for debugging).
  1323. void dump() const;
  1324. /// Export summary to dot file for GraphViz.
  1325. void
  1326. exportToDot(raw_ostream &OS,
  1327. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const;
  1328. /// Print out strongly connected components for debugging.
  1329. void dumpSCCs(raw_ostream &OS);
  1330. /// Do the access attribute and DSOLocal propagation in combined index.
  1331. void propagateAttributes(const DenseSet<GlobalValue::GUID> &PreservedSymbols);
  1332. /// Checks if we can import global variable from another module.
  1333. bool canImportGlobalVar(GlobalValueSummary *S, bool AnalyzeRefs) const;
  1334. };
  1335. /// GraphTraits definition to build SCC for the index
  1336. template <> struct GraphTraits<ValueInfo> {
  1337. typedef ValueInfo NodeRef;
  1338. using EdgeRef = FunctionSummary::EdgeTy &;
  1339. static NodeRef valueInfoFromEdge(FunctionSummary::EdgeTy &P) {
  1340. return P.first;
  1341. }
  1342. using ChildIteratorType =
  1343. mapped_iterator<std::vector<FunctionSummary::EdgeTy>::iterator,
  1344. decltype(&valueInfoFromEdge)>;
  1345. using ChildEdgeIteratorType = std::vector<FunctionSummary::EdgeTy>::iterator;
  1346. static NodeRef getEntryNode(ValueInfo V) { return V; }
  1347. static ChildIteratorType child_begin(NodeRef N) {
  1348. if (!N.getSummaryList().size()) // handle external function
  1349. return ChildIteratorType(
  1350. FunctionSummary::ExternalNode.CallGraphEdgeList.begin(),
  1351. &valueInfoFromEdge);
  1352. FunctionSummary *F =
  1353. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1354. return ChildIteratorType(F->CallGraphEdgeList.begin(), &valueInfoFromEdge);
  1355. }
  1356. static ChildIteratorType child_end(NodeRef N) {
  1357. if (!N.getSummaryList().size()) // handle external function
  1358. return ChildIteratorType(
  1359. FunctionSummary::ExternalNode.CallGraphEdgeList.end(),
  1360. &valueInfoFromEdge);
  1361. FunctionSummary *F =
  1362. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1363. return ChildIteratorType(F->CallGraphEdgeList.end(), &valueInfoFromEdge);
  1364. }
  1365. static ChildEdgeIteratorType child_edge_begin(NodeRef N) {
  1366. if (!N.getSummaryList().size()) // handle external function
  1367. return FunctionSummary::ExternalNode.CallGraphEdgeList.begin();
  1368. FunctionSummary *F =
  1369. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1370. return F->CallGraphEdgeList.begin();
  1371. }
  1372. static ChildEdgeIteratorType child_edge_end(NodeRef N) {
  1373. if (!N.getSummaryList().size()) // handle external function
  1374. return FunctionSummary::ExternalNode.CallGraphEdgeList.end();
  1375. FunctionSummary *F =
  1376. cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
  1377. return F->CallGraphEdgeList.end();
  1378. }
  1379. static NodeRef edge_dest(EdgeRef E) { return E.first; }
  1380. };
  1381. template <>
  1382. struct GraphTraits<ModuleSummaryIndex *> : public GraphTraits<ValueInfo> {
  1383. static NodeRef getEntryNode(ModuleSummaryIndex *I) {
  1384. std::unique_ptr<GlobalValueSummary> Root =
  1385. std::make_unique<FunctionSummary>(I->calculateCallGraphRoot());
  1386. GlobalValueSummaryInfo G(I->haveGVs());
  1387. G.SummaryList.push_back(std::move(Root));
  1388. static auto P =
  1389. GlobalValueSummaryMapTy::value_type(GlobalValue::GUID(0), std::move(G));
  1390. return ValueInfo(I->haveGVs(), &P);
  1391. }
  1392. };
  1393. } // end namespace llvm
  1394. #endif // LLVM_IR_MODULESUMMARYINDEX_H
  1395. #ifdef __GNUC__
  1396. #pragma GCC diagnostic pop
  1397. #endif