WholeProgramDevirt.cpp 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387
  1. //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass implements whole program optimization of virtual calls in cases
  10. // where we know (via !type metadata) that the list of callees is fixed. This
  11. // includes the following:
  12. // - Single implementation devirtualization: if a virtual call has a single
  13. // possible callee, replace all calls with a direct call to that callee.
  14. // - Virtual constant propagation: if the virtual function's return type is an
  15. // integer <=64 bits and all possible callees are readnone, for each class and
  16. // each list of constant arguments: evaluate the function, store the return
  17. // value alongside the virtual table, and rewrite each virtual call as a load
  18. // from the virtual table.
  19. // - Uniform return value optimization: if the conditions for virtual constant
  20. // propagation hold and each function returns the same constant value, replace
  21. // each virtual call with that constant.
  22. // - Unique return value optimization for i1 return values: if the conditions
  23. // for virtual constant propagation hold and a single vtable's function
  24. // returns 0, or a single vtable's function returns 1, replace each virtual
  25. // call with a comparison of the vptr against that vtable's address.
  26. //
  27. // This pass is intended to be used during the regular and thin LTO pipelines:
  28. //
  29. // During regular LTO, the pass determines the best optimization for each
  30. // virtual call and applies the resolutions directly to virtual calls that are
  31. // eligible for virtual call optimization (i.e. calls that use either of the
  32. // llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics).
  33. //
  34. // During hybrid Regular/ThinLTO, the pass operates in two phases:
  35. // - Export phase: this is run during the thin link over a single merged module
  36. // that contains all vtables with !type metadata that participate in the link.
  37. // The pass computes a resolution for each virtual call and stores it in the
  38. // type identifier summary.
  39. // - Import phase: this is run during the thin backends over the individual
  40. // modules. The pass applies the resolutions previously computed during the
  41. // import phase to each eligible virtual call.
  42. //
  43. // During ThinLTO, the pass operates in two phases:
  44. // - Export phase: this is run during the thin link over the index which
  45. // contains a summary of all vtables with !type metadata that participate in
  46. // the link. It computes a resolution for each virtual call and stores it in
  47. // the type identifier summary. Only single implementation devirtualization
  48. // is supported.
  49. // - Import phase: (same as with hybrid case above).
  50. //
  51. //===----------------------------------------------------------------------===//
  52. #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
  53. #include "llvm/ADT/ArrayRef.h"
  54. #include "llvm/ADT/DenseMap.h"
  55. #include "llvm/ADT/DenseMapInfo.h"
  56. #include "llvm/ADT/DenseSet.h"
  57. #include "llvm/ADT/MapVector.h"
  58. #include "llvm/ADT/SmallVector.h"
  59. #include "llvm/ADT/Statistic.h"
  60. #include "llvm/ADT/Triple.h"
  61. #include "llvm/ADT/iterator_range.h"
  62. #include "llvm/Analysis/AssumptionCache.h"
  63. #include "llvm/Analysis/BasicAliasAnalysis.h"
  64. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  65. #include "llvm/Analysis/TypeMetadataUtils.h"
  66. #include "llvm/Bitcode/BitcodeReader.h"
  67. #include "llvm/Bitcode/BitcodeWriter.h"
  68. #include "llvm/IR/Constants.h"
  69. #include "llvm/IR/DataLayout.h"
  70. #include "llvm/IR/DebugLoc.h"
  71. #include "llvm/IR/DerivedTypes.h"
  72. #include "llvm/IR/Dominators.h"
  73. #include "llvm/IR/Function.h"
  74. #include "llvm/IR/GlobalAlias.h"
  75. #include "llvm/IR/GlobalVariable.h"
  76. #include "llvm/IR/IRBuilder.h"
  77. #include "llvm/IR/InstrTypes.h"
  78. #include "llvm/IR/Instruction.h"
  79. #include "llvm/IR/Instructions.h"
  80. #include "llvm/IR/Intrinsics.h"
  81. #include "llvm/IR/LLVMContext.h"
  82. #include "llvm/IR/MDBuilder.h"
  83. #include "llvm/IR/Metadata.h"
  84. #include "llvm/IR/Module.h"
  85. #include "llvm/IR/ModuleSummaryIndexYAML.h"
  86. #include "llvm/InitializePasses.h"
  87. #include "llvm/Pass.h"
  88. #include "llvm/PassRegistry.h"
  89. #include "llvm/Support/Casting.h"
  90. #include "llvm/Support/CommandLine.h"
  91. #include "llvm/Support/Errc.h"
  92. #include "llvm/Support/Error.h"
  93. #include "llvm/Support/FileSystem.h"
  94. #include "llvm/Support/GlobPattern.h"
  95. #include "llvm/Support/MathExtras.h"
  96. #include "llvm/Transforms/IPO.h"
  97. #include "llvm/Transforms/IPO/FunctionAttrs.h"
  98. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  99. #include "llvm/Transforms/Utils/CallPromotionUtils.h"
  100. #include "llvm/Transforms/Utils/Evaluator.h"
  101. #include <algorithm>
  102. #include <cstddef>
  103. #include <map>
  104. #include <set>
  105. #include <string>
  106. using namespace llvm;
  107. using namespace wholeprogramdevirt;
  108. #define DEBUG_TYPE "wholeprogramdevirt"
  109. STATISTIC(NumDevirtTargets, "Number of whole program devirtualization targets");
  110. STATISTIC(NumSingleImpl, "Number of single implementation devirtualizations");
  111. STATISTIC(NumBranchFunnel, "Number of branch funnels");
  112. STATISTIC(NumUniformRetVal, "Number of uniform return value optimizations");
  113. STATISTIC(NumUniqueRetVal, "Number of unique return value optimizations");
  114. STATISTIC(NumVirtConstProp1Bit,
  115. "Number of 1 bit virtual constant propagations");
  116. STATISTIC(NumVirtConstProp, "Number of virtual constant propagations");
  117. static cl::opt<PassSummaryAction> ClSummaryAction(
  118. "wholeprogramdevirt-summary-action",
  119. cl::desc("What to do with the summary when running this pass"),
  120. cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
  121. clEnumValN(PassSummaryAction::Import, "import",
  122. "Import typeid resolutions from summary and globals"),
  123. clEnumValN(PassSummaryAction::Export, "export",
  124. "Export typeid resolutions to summary and globals")),
  125. cl::Hidden);
  126. static cl::opt<std::string> ClReadSummary(
  127. "wholeprogramdevirt-read-summary",
  128. cl::desc(
  129. "Read summary from given bitcode or YAML file before running pass"),
  130. cl::Hidden);
  131. static cl::opt<std::string> ClWriteSummary(
  132. "wholeprogramdevirt-write-summary",
  133. cl::desc("Write summary to given bitcode or YAML file after running pass. "
  134. "Output file format is deduced from extension: *.bc means writing "
  135. "bitcode, otherwise YAML"),
  136. cl::Hidden);
  137. static cl::opt<unsigned>
  138. ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
  139. cl::init(10),
  140. cl::desc("Maximum number of call targets per "
  141. "call site to enable branch funnels"));
  142. static cl::opt<bool>
  143. PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden,
  144. cl::desc("Print index-based devirtualization messages"));
  145. /// Provide a way to force enable whole program visibility in tests.
  146. /// This is needed to support legacy tests that don't contain
  147. /// !vcall_visibility metadata (the mere presense of type tests
  148. /// previously implied hidden visibility).
  149. static cl::opt<bool>
  150. WholeProgramVisibility("whole-program-visibility", cl::Hidden,
  151. cl::desc("Enable whole program visibility"));
  152. /// Provide a way to force disable whole program for debugging or workarounds,
  153. /// when enabled via the linker.
  154. static cl::opt<bool> DisableWholeProgramVisibility(
  155. "disable-whole-program-visibility", cl::Hidden,
  156. cl::desc("Disable whole program visibility (overrides enabling options)"));
  157. /// Provide way to prevent certain function from being devirtualized
  158. static cl::list<std::string>
  159. SkipFunctionNames("wholeprogramdevirt-skip",
  160. cl::desc("Prevent function(s) from being devirtualized"),
  161. cl::Hidden, cl::CommaSeparated);
  162. /// Mechanism to add runtime checking of devirtualization decisions, optionally
  163. /// trapping or falling back to indirect call on any that are not correct.
  164. /// Trapping mode is useful for debugging undefined behavior leading to failures
  165. /// with WPD. Fallback mode is useful for ensuring safety when whole program
  166. /// visibility may be compromised.
  167. enum WPDCheckMode { None, Trap, Fallback };
  168. static cl::opt<WPDCheckMode> DevirtCheckMode(
  169. "wholeprogramdevirt-check", cl::Hidden,
  170. cl::desc("Type of checking for incorrect devirtualizations"),
  171. cl::values(clEnumValN(WPDCheckMode::None, "none", "No checking"),
  172. clEnumValN(WPDCheckMode::Trap, "trap", "Trap when incorrect"),
  173. clEnumValN(WPDCheckMode::Fallback, "fallback",
  174. "Fallback to indirect when incorrect")));
  175. namespace {
  176. struct PatternList {
  177. std::vector<GlobPattern> Patterns;
  178. template <class T> void init(const T &StringList) {
  179. for (const auto &S : StringList)
  180. if (Expected<GlobPattern> Pat = GlobPattern::create(S))
  181. Patterns.push_back(std::move(*Pat));
  182. }
  183. bool match(StringRef S) {
  184. for (const GlobPattern &P : Patterns)
  185. if (P.match(S))
  186. return true;
  187. return false;
  188. }
  189. };
  190. } // namespace
  191. // Find the minimum offset that we may store a value of size Size bits at. If
  192. // IsAfter is set, look for an offset before the object, otherwise look for an
  193. // offset after the object.
  194. uint64_t
  195. wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
  196. bool IsAfter, uint64_t Size) {
  197. // Find a minimum offset taking into account only vtable sizes.
  198. uint64_t MinByte = 0;
  199. for (const VirtualCallTarget &Target : Targets) {
  200. if (IsAfter)
  201. MinByte = std::max(MinByte, Target.minAfterBytes());
  202. else
  203. MinByte = std::max(MinByte, Target.minBeforeBytes());
  204. }
  205. // Build a vector of arrays of bytes covering, for each target, a slice of the
  206. // used region (see AccumBitVector::BytesUsed in
  207. // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
  208. // this aligns the used regions to start at MinByte.
  209. //
  210. // In this example, A, B and C are vtables, # is a byte already allocated for
  211. // a virtual function pointer, AAAA... (etc.) are the used regions for the
  212. // vtables and Offset(X) is the value computed for the Offset variable below
  213. // for X.
  214. //
  215. // Offset(A)
  216. // | |
  217. // |MinByte
  218. // A: ################AAAAAAAA|AAAAAAAA
  219. // B: ########BBBBBBBBBBBBBBBB|BBBB
  220. // C: ########################|CCCCCCCCCCCCCCCC
  221. // | Offset(B) |
  222. //
  223. // This code produces the slices of A, B and C that appear after the divider
  224. // at MinByte.
  225. std::vector<ArrayRef<uint8_t>> Used;
  226. for (const VirtualCallTarget &Target : Targets) {
  227. ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
  228. : Target.TM->Bits->Before.BytesUsed;
  229. uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
  230. : MinByte - Target.minBeforeBytes();
  231. // Disregard used regions that are smaller than Offset. These are
  232. // effectively all-free regions that do not need to be checked.
  233. if (VTUsed.size() > Offset)
  234. Used.push_back(VTUsed.slice(Offset));
  235. }
  236. if (Size == 1) {
  237. // Find a free bit in each member of Used.
  238. for (unsigned I = 0;; ++I) {
  239. uint8_t BitsUsed = 0;
  240. for (auto &&B : Used)
  241. if (I < B.size())
  242. BitsUsed |= B[I];
  243. if (BitsUsed != 0xff)
  244. return (MinByte + I) * 8 + countTrailingZeros(uint8_t(~BitsUsed));
  245. }
  246. } else {
  247. // Find a free (Size/8) byte region in each member of Used.
  248. // FIXME: see if alignment helps.
  249. for (unsigned I = 0;; ++I) {
  250. for (auto &&B : Used) {
  251. unsigned Byte = 0;
  252. while ((I + Byte) < B.size() && Byte < (Size / 8)) {
  253. if (B[I + Byte])
  254. goto NextI;
  255. ++Byte;
  256. }
  257. }
  258. return (MinByte + I) * 8;
  259. NextI:;
  260. }
  261. }
  262. }
  263. void wholeprogramdevirt::setBeforeReturnValues(
  264. MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
  265. unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
  266. if (BitWidth == 1)
  267. OffsetByte = -(AllocBefore / 8 + 1);
  268. else
  269. OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
  270. OffsetBit = AllocBefore % 8;
  271. for (VirtualCallTarget &Target : Targets) {
  272. if (BitWidth == 1)
  273. Target.setBeforeBit(AllocBefore);
  274. else
  275. Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
  276. }
  277. }
  278. void wholeprogramdevirt::setAfterReturnValues(
  279. MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
  280. unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
  281. if (BitWidth == 1)
  282. OffsetByte = AllocAfter / 8;
  283. else
  284. OffsetByte = (AllocAfter + 7) / 8;
  285. OffsetBit = AllocAfter % 8;
  286. for (VirtualCallTarget &Target : Targets) {
  287. if (BitWidth == 1)
  288. Target.setAfterBit(AllocAfter);
  289. else
  290. Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
  291. }
  292. }
  293. VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
  294. : Fn(Fn), TM(TM),
  295. IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
  296. namespace {
  297. // A slot in a set of virtual tables. The TypeID identifies the set of virtual
  298. // tables, and the ByteOffset is the offset in bytes from the address point to
  299. // the virtual function pointer.
  300. struct VTableSlot {
  301. Metadata *TypeID;
  302. uint64_t ByteOffset;
  303. };
  304. } // end anonymous namespace
  305. namespace llvm {
  306. template <> struct DenseMapInfo<VTableSlot> {
  307. static VTableSlot getEmptyKey() {
  308. return {DenseMapInfo<Metadata *>::getEmptyKey(),
  309. DenseMapInfo<uint64_t>::getEmptyKey()};
  310. }
  311. static VTableSlot getTombstoneKey() {
  312. return {DenseMapInfo<Metadata *>::getTombstoneKey(),
  313. DenseMapInfo<uint64_t>::getTombstoneKey()};
  314. }
  315. static unsigned getHashValue(const VTableSlot &I) {
  316. return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
  317. DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
  318. }
  319. static bool isEqual(const VTableSlot &LHS,
  320. const VTableSlot &RHS) {
  321. return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
  322. }
  323. };
  324. template <> struct DenseMapInfo<VTableSlotSummary> {
  325. static VTableSlotSummary getEmptyKey() {
  326. return {DenseMapInfo<StringRef>::getEmptyKey(),
  327. DenseMapInfo<uint64_t>::getEmptyKey()};
  328. }
  329. static VTableSlotSummary getTombstoneKey() {
  330. return {DenseMapInfo<StringRef>::getTombstoneKey(),
  331. DenseMapInfo<uint64_t>::getTombstoneKey()};
  332. }
  333. static unsigned getHashValue(const VTableSlotSummary &I) {
  334. return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^
  335. DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
  336. }
  337. static bool isEqual(const VTableSlotSummary &LHS,
  338. const VTableSlotSummary &RHS) {
  339. return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
  340. }
  341. };
  342. } // end namespace llvm
  343. namespace {
  344. // Returns true if the function must be unreachable based on ValueInfo.
  345. //
  346. // In particular, identifies a function as unreachable in the following
  347. // conditions
  348. // 1) All summaries are live.
  349. // 2) All function summaries indicate it's unreachable
  350. bool mustBeUnreachableFunction(ValueInfo TheFnVI) {
  351. if ((!TheFnVI) || TheFnVI.getSummaryList().empty()) {
  352. // Returns false if ValueInfo is absent, or the summary list is empty
  353. // (e.g., function declarations).
  354. return false;
  355. }
  356. for (const auto &Summary : TheFnVI.getSummaryList()) {
  357. // Conservatively returns false if any non-live functions are seen.
  358. // In general either all summaries should be live or all should be dead.
  359. if (!Summary->isLive())
  360. return false;
  361. if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) {
  362. if (!FS->fflags().MustBeUnreachable)
  363. return false;
  364. }
  365. // Do nothing if a non-function has the same GUID (which is rare).
  366. // This is correct since non-function summaries are not relevant.
  367. }
  368. // All function summaries are live and all of them agree that the function is
  369. // unreachble.
  370. return true;
  371. }
  372. // A virtual call site. VTable is the loaded virtual table pointer, and CS is
  373. // the indirect virtual call.
  374. struct VirtualCallSite {
  375. Value *VTable = nullptr;
  376. CallBase &CB;
  377. // If non-null, this field points to the associated unsafe use count stored in
  378. // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
  379. // of that field for details.
  380. unsigned *NumUnsafeUses = nullptr;
  381. void
  382. emitRemark(const StringRef OptName, const StringRef TargetName,
  383. function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
  384. Function *F = CB.getCaller();
  385. DebugLoc DLoc = CB.getDebugLoc();
  386. BasicBlock *Block = CB.getParent();
  387. using namespace ore;
  388. OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
  389. << NV("Optimization", OptName)
  390. << ": devirtualized a call to "
  391. << NV("FunctionName", TargetName));
  392. }
  393. void replaceAndErase(
  394. const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
  395. function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
  396. Value *New) {
  397. if (RemarksEnabled)
  398. emitRemark(OptName, TargetName, OREGetter);
  399. CB.replaceAllUsesWith(New);
  400. if (auto *II = dyn_cast<InvokeInst>(&CB)) {
  401. BranchInst::Create(II->getNormalDest(), &CB);
  402. II->getUnwindDest()->removePredecessor(II->getParent());
  403. }
  404. CB.eraseFromParent();
  405. // This use is no longer unsafe.
  406. if (NumUnsafeUses)
  407. --*NumUnsafeUses;
  408. }
  409. };
  410. // Call site information collected for a specific VTableSlot and possibly a list
  411. // of constant integer arguments. The grouping by arguments is handled by the
  412. // VTableSlotInfo class.
  413. struct CallSiteInfo {
  414. /// The set of call sites for this slot. Used during regular LTO and the
  415. /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
  416. /// call sites that appear in the merged module itself); in each of these
  417. /// cases we are directly operating on the call sites at the IR level.
  418. std::vector<VirtualCallSite> CallSites;
  419. /// Whether all call sites represented by this CallSiteInfo, including those
  420. /// in summaries, have been devirtualized. This starts off as true because a
  421. /// default constructed CallSiteInfo represents no call sites.
  422. bool AllCallSitesDevirted = true;
  423. // These fields are used during the export phase of ThinLTO and reflect
  424. // information collected from function summaries.
  425. /// Whether any function summary contains an llvm.assume(llvm.type.test) for
  426. /// this slot.
  427. bool SummaryHasTypeTestAssumeUsers = false;
  428. /// CFI-specific: a vector containing the list of function summaries that use
  429. /// the llvm.type.checked.load intrinsic and therefore will require
  430. /// resolutions for llvm.type.test in order to implement CFI checks if
  431. /// devirtualization was unsuccessful. If devirtualization was successful, the
  432. /// pass will clear this vector by calling markDevirt(). If at the end of the
  433. /// pass the vector is non-empty, we will need to add a use of llvm.type.test
  434. /// to each of the function summaries in the vector.
  435. std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
  436. std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
  437. bool isExported() const {
  438. return SummaryHasTypeTestAssumeUsers ||
  439. !SummaryTypeCheckedLoadUsers.empty();
  440. }
  441. void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
  442. SummaryTypeCheckedLoadUsers.push_back(FS);
  443. AllCallSitesDevirted = false;
  444. }
  445. void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
  446. SummaryTypeTestAssumeUsers.push_back(FS);
  447. SummaryHasTypeTestAssumeUsers = true;
  448. AllCallSitesDevirted = false;
  449. }
  450. void markDevirt() {
  451. AllCallSitesDevirted = true;
  452. // As explained in the comment for SummaryTypeCheckedLoadUsers.
  453. SummaryTypeCheckedLoadUsers.clear();
  454. }
  455. };
  456. // Call site information collected for a specific VTableSlot.
  457. struct VTableSlotInfo {
  458. // The set of call sites which do not have all constant integer arguments
  459. // (excluding "this").
  460. CallSiteInfo CSInfo;
  461. // The set of call sites with all constant integer arguments (excluding
  462. // "this"), grouped by argument list.
  463. std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
  464. void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses);
  465. private:
  466. CallSiteInfo &findCallSiteInfo(CallBase &CB);
  467. };
  468. CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) {
  469. std::vector<uint64_t> Args;
  470. auto *CBType = dyn_cast<IntegerType>(CB.getType());
  471. if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty())
  472. return CSInfo;
  473. for (auto &&Arg : drop_begin(CB.args())) {
  474. auto *CI = dyn_cast<ConstantInt>(Arg);
  475. if (!CI || CI->getBitWidth() > 64)
  476. return CSInfo;
  477. Args.push_back(CI->getZExtValue());
  478. }
  479. return ConstCSInfo[Args];
  480. }
  481. void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB,
  482. unsigned *NumUnsafeUses) {
  483. auto &CSI = findCallSiteInfo(CB);
  484. CSI.AllCallSitesDevirted = false;
  485. CSI.CallSites.push_back({VTable, CB, NumUnsafeUses});
  486. }
  487. struct DevirtModule {
  488. Module &M;
  489. function_ref<AAResults &(Function &)> AARGetter;
  490. function_ref<DominatorTree &(Function &)> LookupDomTree;
  491. ModuleSummaryIndex *ExportSummary;
  492. const ModuleSummaryIndex *ImportSummary;
  493. IntegerType *Int8Ty;
  494. PointerType *Int8PtrTy;
  495. IntegerType *Int32Ty;
  496. IntegerType *Int64Ty;
  497. IntegerType *IntPtrTy;
  498. /// Sizeless array type, used for imported vtables. This provides a signal
  499. /// to analyzers that these imports may alias, as they do for example
  500. /// when multiple unique return values occur in the same vtable.
  501. ArrayType *Int8Arr0Ty;
  502. bool RemarksEnabled;
  503. function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
  504. MapVector<VTableSlot, VTableSlotInfo> CallSlots;
  505. // Calls that have already been optimized. We may add a call to multiple
  506. // VTableSlotInfos if vtable loads are coalesced and need to make sure not to
  507. // optimize a call more than once.
  508. SmallPtrSet<CallBase *, 8> OptimizedCalls;
  509. // This map keeps track of the number of "unsafe" uses of a loaded function
  510. // pointer. The key is the associated llvm.type.test intrinsic call generated
  511. // by this pass. An unsafe use is one that calls the loaded function pointer
  512. // directly. Every time we eliminate an unsafe use (for example, by
  513. // devirtualizing it or by applying virtual constant propagation), we
  514. // decrement the value stored in this map. If a value reaches zero, we can
  515. // eliminate the type check by RAUWing the associated llvm.type.test call with
  516. // true.
  517. std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
  518. PatternList FunctionsToSkip;
  519. DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
  520. function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
  521. function_ref<DominatorTree &(Function &)> LookupDomTree,
  522. ModuleSummaryIndex *ExportSummary,
  523. const ModuleSummaryIndex *ImportSummary)
  524. : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree),
  525. ExportSummary(ExportSummary), ImportSummary(ImportSummary),
  526. Int8Ty(Type::getInt8Ty(M.getContext())),
  527. Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
  528. Int32Ty(Type::getInt32Ty(M.getContext())),
  529. Int64Ty(Type::getInt64Ty(M.getContext())),
  530. IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
  531. Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)),
  532. RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
  533. assert(!(ExportSummary && ImportSummary));
  534. FunctionsToSkip.init(SkipFunctionNames);
  535. }
  536. bool areRemarksEnabled();
  537. void
  538. scanTypeTestUsers(Function *TypeTestFunc,
  539. DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
  540. void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
  541. void buildTypeIdentifierMap(
  542. std::vector<VTableBits> &Bits,
  543. DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
  544. bool
  545. tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
  546. const std::set<TypeMemberInfo> &TypeMemberInfos,
  547. uint64_t ByteOffset,
  548. ModuleSummaryIndex *ExportSummary);
  549. void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
  550. bool &IsExported);
  551. bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
  552. MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  553. VTableSlotInfo &SlotInfo,
  554. WholeProgramDevirtResolution *Res);
  555. void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
  556. bool &IsExported);
  557. void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  558. VTableSlotInfo &SlotInfo,
  559. WholeProgramDevirtResolution *Res, VTableSlot Slot);
  560. bool tryEvaluateFunctionsWithArgs(
  561. MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  562. ArrayRef<uint64_t> Args);
  563. void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
  564. uint64_t TheRetVal);
  565. bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  566. CallSiteInfo &CSInfo,
  567. WholeProgramDevirtResolution::ByArg *Res);
  568. // Returns the global symbol name that is used to export information about the
  569. // given vtable slot and list of arguments.
  570. std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
  571. StringRef Name);
  572. bool shouldExportConstantsAsAbsoluteSymbols();
  573. // This function is called during the export phase to create a symbol
  574. // definition containing information about the given vtable slot and list of
  575. // arguments.
  576. void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
  577. Constant *C);
  578. void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
  579. uint32_t Const, uint32_t &Storage);
  580. // This function is called during the import phase to create a reference to
  581. // the symbol definition created during the export phase.
  582. Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
  583. StringRef Name);
  584. Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
  585. StringRef Name, IntegerType *IntTy,
  586. uint32_t Storage);
  587. Constant *getMemberAddr(const TypeMemberInfo *M);
  588. void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
  589. Constant *UniqueMemberAddr);
  590. bool tryUniqueRetValOpt(unsigned BitWidth,
  591. MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  592. CallSiteInfo &CSInfo,
  593. WholeProgramDevirtResolution::ByArg *Res,
  594. VTableSlot Slot, ArrayRef<uint64_t> Args);
  595. void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
  596. Constant *Byte, Constant *Bit);
  597. bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  598. VTableSlotInfo &SlotInfo,
  599. WholeProgramDevirtResolution *Res, VTableSlot Slot);
  600. void rebuildGlobal(VTableBits &B);
  601. // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
  602. void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
  603. // If we were able to eliminate all unsafe uses for a type checked load,
  604. // eliminate the associated type tests by replacing them with true.
  605. void removeRedundantTypeTests();
  606. bool run();
  607. // Look up the corresponding ValueInfo entry of `TheFn` in `ExportSummary`.
  608. //
  609. // Caller guarantees that `ExportSummary` is not nullptr.
  610. static ValueInfo lookUpFunctionValueInfo(Function *TheFn,
  611. ModuleSummaryIndex *ExportSummary);
  612. // Returns true if the function definition must be unreachable.
  613. //
  614. // Note if this helper function returns true, `F` is guaranteed
  615. // to be unreachable; if it returns false, `F` might still
  616. // be unreachable but not covered by this helper function.
  617. //
  618. // Implementation-wise, if function definition is present, IR is analyzed; if
  619. // not, look up function flags from ExportSummary as a fallback.
  620. static bool mustBeUnreachableFunction(Function *const F,
  621. ModuleSummaryIndex *ExportSummary);
  622. // Lower the module using the action and summary passed as command line
  623. // arguments. For testing purposes only.
  624. static bool
  625. runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter,
  626. function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
  627. function_ref<DominatorTree &(Function &)> LookupDomTree);
  628. };
  629. struct DevirtIndex {
  630. ModuleSummaryIndex &ExportSummary;
  631. // The set in which to record GUIDs exported from their module by
  632. // devirtualization, used by client to ensure they are not internalized.
  633. std::set<GlobalValue::GUID> &ExportedGUIDs;
  634. // A map in which to record the information necessary to locate the WPD
  635. // resolution for local targets in case they are exported by cross module
  636. // importing.
  637. std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
  638. MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
  639. PatternList FunctionsToSkip;
  640. DevirtIndex(
  641. ModuleSummaryIndex &ExportSummary,
  642. std::set<GlobalValue::GUID> &ExportedGUIDs,
  643. std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap)
  644. : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
  645. LocalWPDTargetsMap(LocalWPDTargetsMap) {
  646. FunctionsToSkip.init(SkipFunctionNames);
  647. }
  648. bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
  649. const TypeIdCompatibleVtableInfo TIdInfo,
  650. uint64_t ByteOffset);
  651. bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
  652. VTableSlotSummary &SlotSummary,
  653. VTableSlotInfo &SlotInfo,
  654. WholeProgramDevirtResolution *Res,
  655. std::set<ValueInfo> &DevirtTargets);
  656. void run();
  657. };
  658. } // end anonymous namespace
  659. PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
  660. ModuleAnalysisManager &AM) {
  661. auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  662. auto AARGetter = [&](Function &F) -> AAResults & {
  663. return FAM.getResult<AAManager>(F);
  664. };
  665. auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
  666. return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
  667. };
  668. auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {
  669. return FAM.getResult<DominatorTreeAnalysis>(F);
  670. };
  671. if (UseCommandLine) {
  672. if (DevirtModule::runForTesting(M, AARGetter, OREGetter, LookupDomTree))
  673. return PreservedAnalyses::all();
  674. return PreservedAnalyses::none();
  675. }
  676. if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary,
  677. ImportSummary)
  678. .run())
  679. return PreservedAnalyses::all();
  680. return PreservedAnalyses::none();
  681. }
  682. namespace llvm {
  683. // Enable whole program visibility if enabled by client (e.g. linker) or
  684. // internal option, and not force disabled.
  685. bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) {
  686. return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) &&
  687. !DisableWholeProgramVisibility;
  688. }
  689. /// If whole program visibility asserted, then upgrade all public vcall
  690. /// visibility metadata on vtable definitions to linkage unit visibility in
  691. /// Module IR (for regular or hybrid LTO).
  692. void updateVCallVisibilityInModule(
  693. Module &M, bool WholeProgramVisibilityEnabledInLTO,
  694. const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) {
  695. if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
  696. return;
  697. for (GlobalVariable &GV : M.globals()) {
  698. // Add linkage unit visibility to any variable with type metadata, which are
  699. // the vtable definitions. We won't have an existing vcall_visibility
  700. // metadata on vtable definitions with public visibility.
  701. if (GV.hasMetadata(LLVMContext::MD_type) &&
  702. GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic &&
  703. // Don't upgrade the visibility for symbols exported to the dynamic
  704. // linker, as we have no information on their eventual use.
  705. !DynamicExportSymbols.count(GV.getGUID()))
  706. GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit);
  707. }
  708. }
  709. void updatePublicTypeTestCalls(Module &M,
  710. bool WholeProgramVisibilityEnabledInLTO) {
  711. Function *PublicTypeTestFunc =
  712. M.getFunction(Intrinsic::getName(Intrinsic::public_type_test));
  713. if (!PublicTypeTestFunc)
  714. return;
  715. if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) {
  716. Function *TypeTestFunc =
  717. Intrinsic::getDeclaration(&M, Intrinsic::type_test);
  718. for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
  719. auto *CI = cast<CallInst>(U.getUser());
  720. auto *NewCI = CallInst::Create(
  721. TypeTestFunc, {CI->getArgOperand(0), CI->getArgOperand(1)},
  722. std::nullopt, "", CI);
  723. CI->replaceAllUsesWith(NewCI);
  724. CI->eraseFromParent();
  725. }
  726. } else {
  727. auto *True = ConstantInt::getTrue(M.getContext());
  728. for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
  729. auto *CI = cast<CallInst>(U.getUser());
  730. CI->replaceAllUsesWith(True);
  731. CI->eraseFromParent();
  732. }
  733. }
  734. }
  735. /// If whole program visibility asserted, then upgrade all public vcall
  736. /// visibility metadata on vtable definition summaries to linkage unit
  737. /// visibility in Module summary index (for ThinLTO).
  738. void updateVCallVisibilityInIndex(
  739. ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO,
  740. const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) {
  741. if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
  742. return;
  743. for (auto &P : Index) {
  744. // Don't upgrade the visibility for symbols exported to the dynamic
  745. // linker, as we have no information on their eventual use.
  746. if (DynamicExportSymbols.count(P.first))
  747. continue;
  748. for (auto &S : P.second.SummaryList) {
  749. auto *GVar = dyn_cast<GlobalVarSummary>(S.get());
  750. if (!GVar ||
  751. GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic)
  752. continue;
  753. GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit);
  754. }
  755. }
  756. }
  757. void runWholeProgramDevirtOnIndex(
  758. ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
  759. std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
  760. DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run();
  761. }
  762. void updateIndexWPDForExports(
  763. ModuleSummaryIndex &Summary,
  764. function_ref<bool(StringRef, ValueInfo)> isExported,
  765. std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
  766. for (auto &T : LocalWPDTargetsMap) {
  767. auto &VI = T.first;
  768. // This was enforced earlier during trySingleImplDevirt.
  769. assert(VI.getSummaryList().size() == 1 &&
  770. "Devirt of local target has more than one copy");
  771. auto &S = VI.getSummaryList()[0];
  772. if (!isExported(S->modulePath(), VI))
  773. continue;
  774. // It's been exported by a cross module import.
  775. for (auto &SlotSummary : T.second) {
  776. auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
  777. assert(TIdSum);
  778. auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
  779. assert(WPDRes != TIdSum->WPDRes.end());
  780. WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
  781. WPDRes->second.SingleImplName,
  782. Summary.getModuleHash(S->modulePath()));
  783. }
  784. }
  785. }
  786. } // end namespace llvm
  787. static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) {
  788. // Check that summary index contains regular LTO module when performing
  789. // export to prevent occasional use of index from pure ThinLTO compilation
  790. // (-fno-split-lto-module). This kind of summary index is passed to
  791. // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting.
  792. const auto &ModPaths = Summary->modulePaths();
  793. if (ClSummaryAction != PassSummaryAction::Import &&
  794. ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) ==
  795. ModPaths.end())
  796. return createStringError(
  797. errc::invalid_argument,
  798. "combined summary should contain Regular LTO module");
  799. return ErrorSuccess();
  800. }
  801. bool DevirtModule::runForTesting(
  802. Module &M, function_ref<AAResults &(Function &)> AARGetter,
  803. function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
  804. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  805. std::unique_ptr<ModuleSummaryIndex> Summary =
  806. std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
  807. // Handle the command-line summary arguments. This code is for testing
  808. // purposes only, so we handle errors directly.
  809. if (!ClReadSummary.empty()) {
  810. ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
  811. ": ");
  812. auto ReadSummaryFile =
  813. ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
  814. if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
  815. getModuleSummaryIndex(*ReadSummaryFile)) {
  816. Summary = std::move(*SummaryOrErr);
  817. ExitOnErr(checkCombinedSummaryForTesting(Summary.get()));
  818. } else {
  819. // Try YAML if we've failed with bitcode.
  820. consumeError(SummaryOrErr.takeError());
  821. yaml::Input In(ReadSummaryFile->getBuffer());
  822. In >> *Summary;
  823. ExitOnErr(errorCodeToError(In.error()));
  824. }
  825. }
  826. bool Changed =
  827. DevirtModule(M, AARGetter, OREGetter, LookupDomTree,
  828. ClSummaryAction == PassSummaryAction::Export ? Summary.get()
  829. : nullptr,
  830. ClSummaryAction == PassSummaryAction::Import ? Summary.get()
  831. : nullptr)
  832. .run();
  833. if (!ClWriteSummary.empty()) {
  834. ExitOnError ExitOnErr(
  835. "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
  836. std::error_code EC;
  837. if (StringRef(ClWriteSummary).endswith(".bc")) {
  838. raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None);
  839. ExitOnErr(errorCodeToError(EC));
  840. writeIndexToFile(*Summary, OS);
  841. } else {
  842. raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_TextWithCRLF);
  843. ExitOnErr(errorCodeToError(EC));
  844. yaml::Output Out(OS);
  845. Out << *Summary;
  846. }
  847. }
  848. return Changed;
  849. }
  850. void DevirtModule::buildTypeIdentifierMap(
  851. std::vector<VTableBits> &Bits,
  852. DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
  853. DenseMap<GlobalVariable *, VTableBits *> GVToBits;
  854. Bits.reserve(M.getGlobalList().size());
  855. SmallVector<MDNode *, 2> Types;
  856. for (GlobalVariable &GV : M.globals()) {
  857. Types.clear();
  858. GV.getMetadata(LLVMContext::MD_type, Types);
  859. if (GV.isDeclaration() || Types.empty())
  860. continue;
  861. VTableBits *&BitsPtr = GVToBits[&GV];
  862. if (!BitsPtr) {
  863. Bits.emplace_back();
  864. Bits.back().GV = &GV;
  865. Bits.back().ObjectSize =
  866. M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
  867. BitsPtr = &Bits.back();
  868. }
  869. for (MDNode *Type : Types) {
  870. auto TypeID = Type->getOperand(1).get();
  871. uint64_t Offset =
  872. cast<ConstantInt>(
  873. cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
  874. ->getZExtValue();
  875. TypeIdMap[TypeID].insert({BitsPtr, Offset});
  876. }
  877. }
  878. }
  879. bool DevirtModule::tryFindVirtualCallTargets(
  880. std::vector<VirtualCallTarget> &TargetsForSlot,
  881. const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset,
  882. ModuleSummaryIndex *ExportSummary) {
  883. for (const TypeMemberInfo &TM : TypeMemberInfos) {
  884. if (!TM.Bits->GV->isConstant())
  885. return false;
  886. // We cannot perform whole program devirtualization analysis on a vtable
  887. // with public LTO visibility.
  888. if (TM.Bits->GV->getVCallVisibility() ==
  889. GlobalObject::VCallVisibilityPublic)
  890. return false;
  891. Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
  892. TM.Offset + ByteOffset, M);
  893. if (!Ptr)
  894. return false;
  895. auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
  896. if (!Fn)
  897. return false;
  898. if (FunctionsToSkip.match(Fn->getName()))
  899. return false;
  900. // We can disregard __cxa_pure_virtual as a possible call target, as
  901. // calls to pure virtuals are UB.
  902. if (Fn->getName() == "__cxa_pure_virtual")
  903. continue;
  904. // We can disregard unreachable functions as possible call targets, as
  905. // unreachable functions shouldn't be called.
  906. if (mustBeUnreachableFunction(Fn, ExportSummary))
  907. continue;
  908. TargetsForSlot.push_back({Fn, &TM});
  909. }
  910. // Give up if we couldn't find any targets.
  911. return !TargetsForSlot.empty();
  912. }
  913. bool DevirtIndex::tryFindVirtualCallTargets(
  914. std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo,
  915. uint64_t ByteOffset) {
  916. for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
  917. // Find a representative copy of the vtable initializer.
  918. // We can have multiple available_externally, linkonce_odr and weak_odr
  919. // vtable initializers. We can also have multiple external vtable
  920. // initializers in the case of comdats, which we cannot check here.
  921. // The linker should give an error in this case.
  922. //
  923. // Also, handle the case of same-named local Vtables with the same path
  924. // and therefore the same GUID. This can happen if there isn't enough
  925. // distinguishing path when compiling the source file. In that case we
  926. // conservatively return false early.
  927. const GlobalVarSummary *VS = nullptr;
  928. bool LocalFound = false;
  929. for (const auto &S : P.VTableVI.getSummaryList()) {
  930. if (GlobalValue::isLocalLinkage(S->linkage())) {
  931. if (LocalFound)
  932. return false;
  933. LocalFound = true;
  934. }
  935. auto *CurVS = cast<GlobalVarSummary>(S->getBaseObject());
  936. if (!CurVS->vTableFuncs().empty() ||
  937. // Previously clang did not attach the necessary type metadata to
  938. // available_externally vtables, in which case there would not
  939. // be any vtable functions listed in the summary and we need
  940. // to treat this case conservatively (in case the bitcode is old).
  941. // However, we will also not have any vtable functions in the
  942. // case of a pure virtual base class. In that case we do want
  943. // to set VS to avoid treating it conservatively.
  944. !GlobalValue::isAvailableExternallyLinkage(S->linkage())) {
  945. VS = CurVS;
  946. // We cannot perform whole program devirtualization analysis on a vtable
  947. // with public LTO visibility.
  948. if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
  949. return false;
  950. }
  951. }
  952. // There will be no VS if all copies are available_externally having no
  953. // type metadata. In that case we can't safely perform WPD.
  954. if (!VS)
  955. return false;
  956. if (!VS->isLive())
  957. continue;
  958. for (auto VTP : VS->vTableFuncs()) {
  959. if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
  960. continue;
  961. if (mustBeUnreachableFunction(VTP.FuncVI))
  962. continue;
  963. TargetsForSlot.push_back(VTP.FuncVI);
  964. }
  965. }
  966. // Give up if we couldn't find any targets.
  967. return !TargetsForSlot.empty();
  968. }
  969. void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
  970. Constant *TheFn, bool &IsExported) {
  971. // Don't devirtualize function if we're told to skip it
  972. // in -wholeprogramdevirt-skip.
  973. if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName()))
  974. return;
  975. auto Apply = [&](CallSiteInfo &CSInfo) {
  976. for (auto &&VCallSite : CSInfo.CallSites) {
  977. if (!OptimizedCalls.insert(&VCallSite.CB).second)
  978. continue;
  979. if (RemarksEnabled)
  980. VCallSite.emitRemark("single-impl",
  981. TheFn->stripPointerCasts()->getName(), OREGetter);
  982. NumSingleImpl++;
  983. auto &CB = VCallSite.CB;
  984. assert(!CB.getCalledFunction() && "devirtualizing direct call?");
  985. IRBuilder<> Builder(&CB);
  986. Value *Callee =
  987. Builder.CreateBitCast(TheFn, CB.getCalledOperand()->getType());
  988. // If trap checking is enabled, add support to compare the virtual
  989. // function pointer to the devirtualized target. In case of a mismatch,
  990. // perform a debug trap.
  991. if (DevirtCheckMode == WPDCheckMode::Trap) {
  992. auto *Cond = Builder.CreateICmpNE(CB.getCalledOperand(), Callee);
  993. Instruction *ThenTerm =
  994. SplitBlockAndInsertIfThen(Cond, &CB, /*Unreachable=*/false);
  995. Builder.SetInsertPoint(ThenTerm);
  996. Function *TrapFn = Intrinsic::getDeclaration(&M, Intrinsic::debugtrap);
  997. auto *CallTrap = Builder.CreateCall(TrapFn);
  998. CallTrap->setDebugLoc(CB.getDebugLoc());
  999. }
  1000. // If fallback checking is enabled, add support to compare the virtual
  1001. // function pointer to the devirtualized target. In case of a mismatch,
  1002. // fall back to indirect call.
  1003. if (DevirtCheckMode == WPDCheckMode::Fallback) {
  1004. MDNode *Weights =
  1005. MDBuilder(M.getContext()).createBranchWeights((1U << 20) - 1, 1);
  1006. // Version the indirect call site. If the called value is equal to the
  1007. // given callee, 'NewInst' will be executed, otherwise the original call
  1008. // site will be executed.
  1009. CallBase &NewInst = versionCallSite(CB, Callee, Weights);
  1010. NewInst.setCalledOperand(Callee);
  1011. // Since the new call site is direct, we must clear metadata that
  1012. // is only appropriate for indirect calls. This includes !prof and
  1013. // !callees metadata.
  1014. NewInst.setMetadata(LLVMContext::MD_prof, nullptr);
  1015. NewInst.setMetadata(LLVMContext::MD_callees, nullptr);
  1016. // Additionally, we should remove them from the fallback indirect call,
  1017. // so that we don't attempt to perform indirect call promotion later.
  1018. CB.setMetadata(LLVMContext::MD_prof, nullptr);
  1019. CB.setMetadata(LLVMContext::MD_callees, nullptr);
  1020. }
  1021. // In either trapping or non-checking mode, devirtualize original call.
  1022. else {
  1023. // Devirtualize unconditionally.
  1024. CB.setCalledOperand(Callee);
  1025. // Since the call site is now direct, we must clear metadata that
  1026. // is only appropriate for indirect calls. This includes !prof and
  1027. // !callees metadata.
  1028. CB.setMetadata(LLVMContext::MD_prof, nullptr);
  1029. CB.setMetadata(LLVMContext::MD_callees, nullptr);
  1030. }
  1031. // This use is no longer unsafe.
  1032. if (VCallSite.NumUnsafeUses)
  1033. --*VCallSite.NumUnsafeUses;
  1034. }
  1035. if (CSInfo.isExported())
  1036. IsExported = true;
  1037. CSInfo.markDevirt();
  1038. };
  1039. Apply(SlotInfo.CSInfo);
  1040. for (auto &P : SlotInfo.ConstCSInfo)
  1041. Apply(P.second);
  1042. }
  1043. static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
  1044. // We can't add calls if we haven't seen a definition
  1045. if (Callee.getSummaryList().empty())
  1046. return false;
  1047. // Insert calls into the summary index so that the devirtualized targets
  1048. // are eligible for import.
  1049. // FIXME: Annotate type tests with hotness. For now, mark these as hot
  1050. // to better ensure we have the opportunity to inline them.
  1051. bool IsExported = false;
  1052. auto &S = Callee.getSummaryList()[0];
  1053. CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0);
  1054. auto AddCalls = [&](CallSiteInfo &CSInfo) {
  1055. for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
  1056. FS->addCall({Callee, CI});
  1057. IsExported |= S->modulePath() != FS->modulePath();
  1058. }
  1059. for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
  1060. FS->addCall({Callee, CI});
  1061. IsExported |= S->modulePath() != FS->modulePath();
  1062. }
  1063. };
  1064. AddCalls(SlotInfo.CSInfo);
  1065. for (auto &P : SlotInfo.ConstCSInfo)
  1066. AddCalls(P.second);
  1067. return IsExported;
  1068. }
  1069. bool DevirtModule::trySingleImplDevirt(
  1070. ModuleSummaryIndex *ExportSummary,
  1071. MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
  1072. WholeProgramDevirtResolution *Res) {
  1073. // See if the program contains a single implementation of this virtual
  1074. // function.
  1075. Function *TheFn = TargetsForSlot[0].Fn;
  1076. for (auto &&Target : TargetsForSlot)
  1077. if (TheFn != Target.Fn)
  1078. return false;
  1079. // If so, update each call site to call that implementation directly.
  1080. if (RemarksEnabled || AreStatisticsEnabled())
  1081. TargetsForSlot[0].WasDevirt = true;
  1082. bool IsExported = false;
  1083. applySingleImplDevirt(SlotInfo, TheFn, IsExported);
  1084. if (!IsExported)
  1085. return false;
  1086. // If the only implementation has local linkage, we must promote to external
  1087. // to make it visible to thin LTO objects. We can only get here during the
  1088. // ThinLTO export phase.
  1089. if (TheFn->hasLocalLinkage()) {
  1090. std::string NewName = (TheFn->getName() + ".llvm.merged").str();
  1091. // Since we are renaming the function, any comdats with the same name must
  1092. // also be renamed. This is required when targeting COFF, as the comdat name
  1093. // must match one of the names of the symbols in the comdat.
  1094. if (Comdat *C = TheFn->getComdat()) {
  1095. if (C->getName() == TheFn->getName()) {
  1096. Comdat *NewC = M.getOrInsertComdat(NewName);
  1097. NewC->setSelectionKind(C->getSelectionKind());
  1098. for (GlobalObject &GO : M.global_objects())
  1099. if (GO.getComdat() == C)
  1100. GO.setComdat(NewC);
  1101. }
  1102. }
  1103. TheFn->setLinkage(GlobalValue::ExternalLinkage);
  1104. TheFn->setVisibility(GlobalValue::HiddenVisibility);
  1105. TheFn->setName(NewName);
  1106. }
  1107. if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
  1108. // Any needed promotion of 'TheFn' has already been done during
  1109. // LTO unit split, so we can ignore return value of AddCalls.
  1110. AddCalls(SlotInfo, TheFnVI);
  1111. Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
  1112. Res->SingleImplName = std::string(TheFn->getName());
  1113. return true;
  1114. }
  1115. bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
  1116. VTableSlotSummary &SlotSummary,
  1117. VTableSlotInfo &SlotInfo,
  1118. WholeProgramDevirtResolution *Res,
  1119. std::set<ValueInfo> &DevirtTargets) {
  1120. // See if the program contains a single implementation of this virtual
  1121. // function.
  1122. auto TheFn = TargetsForSlot[0];
  1123. for (auto &&Target : TargetsForSlot)
  1124. if (TheFn != Target)
  1125. return false;
  1126. // Don't devirtualize if we don't have target definition.
  1127. auto Size = TheFn.getSummaryList().size();
  1128. if (!Size)
  1129. return false;
  1130. // Don't devirtualize function if we're told to skip it
  1131. // in -wholeprogramdevirt-skip.
  1132. if (FunctionsToSkip.match(TheFn.name()))
  1133. return false;
  1134. // If the summary list contains multiple summaries where at least one is
  1135. // a local, give up, as we won't know which (possibly promoted) name to use.
  1136. for (const auto &S : TheFn.getSummaryList())
  1137. if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1)
  1138. return false;
  1139. // Collect functions devirtualized at least for one call site for stats.
  1140. if (PrintSummaryDevirt || AreStatisticsEnabled())
  1141. DevirtTargets.insert(TheFn);
  1142. auto &S = TheFn.getSummaryList()[0];
  1143. bool IsExported = AddCalls(SlotInfo, TheFn);
  1144. if (IsExported)
  1145. ExportedGUIDs.insert(TheFn.getGUID());
  1146. // Record in summary for use in devirtualization during the ThinLTO import
  1147. // step.
  1148. Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
  1149. if (GlobalValue::isLocalLinkage(S->linkage())) {
  1150. if (IsExported)
  1151. // If target is a local function and we are exporting it by
  1152. // devirtualizing a call in another module, we need to record the
  1153. // promoted name.
  1154. Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
  1155. TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
  1156. else {
  1157. LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
  1158. Res->SingleImplName = std::string(TheFn.name());
  1159. }
  1160. } else
  1161. Res->SingleImplName = std::string(TheFn.name());
  1162. // Name will be empty if this thin link driven off of serialized combined
  1163. // index (e.g. llvm-lto). However, WPD is not supported/invoked for the
  1164. // legacy LTO API anyway.
  1165. assert(!Res->SingleImplName.empty());
  1166. return true;
  1167. }
  1168. void DevirtModule::tryICallBranchFunnel(
  1169. MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
  1170. WholeProgramDevirtResolution *Res, VTableSlot Slot) {
  1171. Triple T(M.getTargetTriple());
  1172. if (T.getArch() != Triple::x86_64)
  1173. return;
  1174. if (TargetsForSlot.size() > ClThreshold)
  1175. return;
  1176. bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
  1177. if (!HasNonDevirt)
  1178. for (auto &P : SlotInfo.ConstCSInfo)
  1179. if (!P.second.AllCallSitesDevirted) {
  1180. HasNonDevirt = true;
  1181. break;
  1182. }
  1183. if (!HasNonDevirt)
  1184. return;
  1185. FunctionType *FT =
  1186. FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
  1187. Function *JT;
  1188. if (isa<MDString>(Slot.TypeID)) {
  1189. JT = Function::Create(FT, Function::ExternalLinkage,
  1190. M.getDataLayout().getProgramAddressSpace(),
  1191. getGlobalName(Slot, {}, "branch_funnel"), &M);
  1192. JT->setVisibility(GlobalValue::HiddenVisibility);
  1193. } else {
  1194. JT = Function::Create(FT, Function::InternalLinkage,
  1195. M.getDataLayout().getProgramAddressSpace(),
  1196. "branch_funnel", &M);
  1197. }
  1198. JT->addParamAttr(0, Attribute::Nest);
  1199. std::vector<Value *> JTArgs;
  1200. JTArgs.push_back(JT->arg_begin());
  1201. for (auto &T : TargetsForSlot) {
  1202. JTArgs.push_back(getMemberAddr(T.TM));
  1203. JTArgs.push_back(T.Fn);
  1204. }
  1205. BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
  1206. Function *Intr =
  1207. Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
  1208. auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
  1209. CI->setTailCallKind(CallInst::TCK_MustTail);
  1210. ReturnInst::Create(M.getContext(), nullptr, BB);
  1211. bool IsExported = false;
  1212. applyICallBranchFunnel(SlotInfo, JT, IsExported);
  1213. if (IsExported)
  1214. Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
  1215. }
  1216. void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
  1217. Constant *JT, bool &IsExported) {
  1218. auto Apply = [&](CallSiteInfo &CSInfo) {
  1219. if (CSInfo.isExported())
  1220. IsExported = true;
  1221. if (CSInfo.AllCallSitesDevirted)
  1222. return;
  1223. for (auto &&VCallSite : CSInfo.CallSites) {
  1224. CallBase &CB = VCallSite.CB;
  1225. // Jump tables are only profitable if the retpoline mitigation is enabled.
  1226. Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features");
  1227. if (!FSAttr.isValid() ||
  1228. !FSAttr.getValueAsString().contains("+retpoline"))
  1229. continue;
  1230. NumBranchFunnel++;
  1231. if (RemarksEnabled)
  1232. VCallSite.emitRemark("branch-funnel",
  1233. JT->stripPointerCasts()->getName(), OREGetter);
  1234. // Pass the address of the vtable in the nest register, which is r10 on
  1235. // x86_64.
  1236. std::vector<Type *> NewArgs;
  1237. NewArgs.push_back(Int8PtrTy);
  1238. append_range(NewArgs, CB.getFunctionType()->params());
  1239. FunctionType *NewFT =
  1240. FunctionType::get(CB.getFunctionType()->getReturnType(), NewArgs,
  1241. CB.getFunctionType()->isVarArg());
  1242. PointerType *NewFTPtr = PointerType::getUnqual(NewFT);
  1243. IRBuilder<> IRB(&CB);
  1244. std::vector<Value *> Args;
  1245. Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
  1246. llvm::append_range(Args, CB.args());
  1247. CallBase *NewCS = nullptr;
  1248. if (isa<CallInst>(CB))
  1249. NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args);
  1250. else
  1251. NewCS = IRB.CreateInvoke(NewFT, IRB.CreateBitCast(JT, NewFTPtr),
  1252. cast<InvokeInst>(CB).getNormalDest(),
  1253. cast<InvokeInst>(CB).getUnwindDest(), Args);
  1254. NewCS->setCallingConv(CB.getCallingConv());
  1255. AttributeList Attrs = CB.getAttributes();
  1256. std::vector<AttributeSet> NewArgAttrs;
  1257. NewArgAttrs.push_back(AttributeSet::get(
  1258. M.getContext(), ArrayRef<Attribute>{Attribute::get(
  1259. M.getContext(), Attribute::Nest)}));
  1260. for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
  1261. NewArgAttrs.push_back(Attrs.getParamAttrs(I));
  1262. NewCS->setAttributes(
  1263. AttributeList::get(M.getContext(), Attrs.getFnAttrs(),
  1264. Attrs.getRetAttrs(), NewArgAttrs));
  1265. CB.replaceAllUsesWith(NewCS);
  1266. CB.eraseFromParent();
  1267. // This use is no longer unsafe.
  1268. if (VCallSite.NumUnsafeUses)
  1269. --*VCallSite.NumUnsafeUses;
  1270. }
  1271. // Don't mark as devirtualized because there may be callers compiled without
  1272. // retpoline mitigation, which would mean that they are lowered to
  1273. // llvm.type.test and therefore require an llvm.type.test resolution for the
  1274. // type identifier.
  1275. };
  1276. Apply(SlotInfo.CSInfo);
  1277. for (auto &P : SlotInfo.ConstCSInfo)
  1278. Apply(P.second);
  1279. }
  1280. bool DevirtModule::tryEvaluateFunctionsWithArgs(
  1281. MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  1282. ArrayRef<uint64_t> Args) {
  1283. // Evaluate each function and store the result in each target's RetVal
  1284. // field.
  1285. for (VirtualCallTarget &Target : TargetsForSlot) {
  1286. if (Target.Fn->arg_size() != Args.size() + 1)
  1287. return false;
  1288. Evaluator Eval(M.getDataLayout(), nullptr);
  1289. SmallVector<Constant *, 2> EvalArgs;
  1290. EvalArgs.push_back(
  1291. Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
  1292. for (unsigned I = 0; I != Args.size(); ++I) {
  1293. auto *ArgTy = dyn_cast<IntegerType>(
  1294. Target.Fn->getFunctionType()->getParamType(I + 1));
  1295. if (!ArgTy)
  1296. return false;
  1297. EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
  1298. }
  1299. Constant *RetVal;
  1300. if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
  1301. !isa<ConstantInt>(RetVal))
  1302. return false;
  1303. Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
  1304. }
  1305. return true;
  1306. }
  1307. void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
  1308. uint64_t TheRetVal) {
  1309. for (auto Call : CSInfo.CallSites) {
  1310. if (!OptimizedCalls.insert(&Call.CB).second)
  1311. continue;
  1312. NumUniformRetVal++;
  1313. Call.replaceAndErase(
  1314. "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
  1315. ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal));
  1316. }
  1317. CSInfo.markDevirt();
  1318. }
  1319. bool DevirtModule::tryUniformRetValOpt(
  1320. MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
  1321. WholeProgramDevirtResolution::ByArg *Res) {
  1322. // Uniform return value optimization. If all functions return the same
  1323. // constant, replace all calls with that constant.
  1324. uint64_t TheRetVal = TargetsForSlot[0].RetVal;
  1325. for (const VirtualCallTarget &Target : TargetsForSlot)
  1326. if (Target.RetVal != TheRetVal)
  1327. return false;
  1328. if (CSInfo.isExported()) {
  1329. Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
  1330. Res->Info = TheRetVal;
  1331. }
  1332. applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
  1333. if (RemarksEnabled || AreStatisticsEnabled())
  1334. for (auto &&Target : TargetsForSlot)
  1335. Target.WasDevirt = true;
  1336. return true;
  1337. }
  1338. std::string DevirtModule::getGlobalName(VTableSlot Slot,
  1339. ArrayRef<uint64_t> Args,
  1340. StringRef Name) {
  1341. std::string FullName = "__typeid_";
  1342. raw_string_ostream OS(FullName);
  1343. OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
  1344. for (uint64_t Arg : Args)
  1345. OS << '_' << Arg;
  1346. OS << '_' << Name;
  1347. return OS.str();
  1348. }
  1349. bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
  1350. Triple T(M.getTargetTriple());
  1351. return T.isX86() && T.getObjectFormat() == Triple::ELF;
  1352. }
  1353. void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
  1354. StringRef Name, Constant *C) {
  1355. GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
  1356. getGlobalName(Slot, Args, Name), C, &M);
  1357. GA->setVisibility(GlobalValue::HiddenVisibility);
  1358. }
  1359. void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
  1360. StringRef Name, uint32_t Const,
  1361. uint32_t &Storage) {
  1362. if (shouldExportConstantsAsAbsoluteSymbols()) {
  1363. exportGlobal(
  1364. Slot, Args, Name,
  1365. ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
  1366. return;
  1367. }
  1368. Storage = Const;
  1369. }
  1370. Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
  1371. StringRef Name) {
  1372. Constant *C =
  1373. M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty);
  1374. auto *GV = dyn_cast<GlobalVariable>(C);
  1375. if (GV)
  1376. GV->setVisibility(GlobalValue::HiddenVisibility);
  1377. return C;
  1378. }
  1379. Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
  1380. StringRef Name, IntegerType *IntTy,
  1381. uint32_t Storage) {
  1382. if (!shouldExportConstantsAsAbsoluteSymbols())
  1383. return ConstantInt::get(IntTy, Storage);
  1384. Constant *C = importGlobal(Slot, Args, Name);
  1385. auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
  1386. C = ConstantExpr::getPtrToInt(C, IntTy);
  1387. // We only need to set metadata if the global is newly created, in which
  1388. // case it would not have hidden visibility.
  1389. if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
  1390. return C;
  1391. auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
  1392. auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
  1393. auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
  1394. GV->setMetadata(LLVMContext::MD_absolute_symbol,
  1395. MDNode::get(M.getContext(), {MinC, MaxC}));
  1396. };
  1397. unsigned AbsWidth = IntTy->getBitWidth();
  1398. if (AbsWidth == IntPtrTy->getBitWidth())
  1399. SetAbsRange(~0ull, ~0ull); // Full set.
  1400. else
  1401. SetAbsRange(0, 1ull << AbsWidth);
  1402. return C;
  1403. }
  1404. void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
  1405. bool IsOne,
  1406. Constant *UniqueMemberAddr) {
  1407. for (auto &&Call : CSInfo.CallSites) {
  1408. if (!OptimizedCalls.insert(&Call.CB).second)
  1409. continue;
  1410. IRBuilder<> B(&Call.CB);
  1411. Value *Cmp =
  1412. B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable,
  1413. B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType()));
  1414. Cmp = B.CreateZExt(Cmp, Call.CB.getType());
  1415. NumUniqueRetVal++;
  1416. Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
  1417. Cmp);
  1418. }
  1419. CSInfo.markDevirt();
  1420. }
  1421. Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
  1422. Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
  1423. return ConstantExpr::getGetElementPtr(Int8Ty, C,
  1424. ConstantInt::get(Int64Ty, M->Offset));
  1425. }
  1426. bool DevirtModule::tryUniqueRetValOpt(
  1427. unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
  1428. CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
  1429. VTableSlot Slot, ArrayRef<uint64_t> Args) {
  1430. // IsOne controls whether we look for a 0 or a 1.
  1431. auto tryUniqueRetValOptFor = [&](bool IsOne) {
  1432. const TypeMemberInfo *UniqueMember = nullptr;
  1433. for (const VirtualCallTarget &Target : TargetsForSlot) {
  1434. if (Target.RetVal == (IsOne ? 1 : 0)) {
  1435. if (UniqueMember)
  1436. return false;
  1437. UniqueMember = Target.TM;
  1438. }
  1439. }
  1440. // We should have found a unique member or bailed out by now. We already
  1441. // checked for a uniform return value in tryUniformRetValOpt.
  1442. assert(UniqueMember);
  1443. Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
  1444. if (CSInfo.isExported()) {
  1445. Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
  1446. Res->Info = IsOne;
  1447. exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
  1448. }
  1449. // Replace each call with the comparison.
  1450. applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
  1451. UniqueMemberAddr);
  1452. // Update devirtualization statistics for targets.
  1453. if (RemarksEnabled || AreStatisticsEnabled())
  1454. for (auto &&Target : TargetsForSlot)
  1455. Target.WasDevirt = true;
  1456. return true;
  1457. };
  1458. if (BitWidth == 1) {
  1459. if (tryUniqueRetValOptFor(true))
  1460. return true;
  1461. if (tryUniqueRetValOptFor(false))
  1462. return true;
  1463. }
  1464. return false;
  1465. }
  1466. void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
  1467. Constant *Byte, Constant *Bit) {
  1468. for (auto Call : CSInfo.CallSites) {
  1469. if (!OptimizedCalls.insert(&Call.CB).second)
  1470. continue;
  1471. auto *RetType = cast<IntegerType>(Call.CB.getType());
  1472. IRBuilder<> B(&Call.CB);
  1473. Value *Addr =
  1474. B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
  1475. if (RetType->getBitWidth() == 1) {
  1476. Value *Bits = B.CreateLoad(Int8Ty, Addr);
  1477. Value *BitsAndBit = B.CreateAnd(Bits, Bit);
  1478. auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
  1479. NumVirtConstProp1Bit++;
  1480. Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
  1481. OREGetter, IsBitSet);
  1482. } else {
  1483. Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
  1484. Value *Val = B.CreateLoad(RetType, ValAddr);
  1485. NumVirtConstProp++;
  1486. Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
  1487. OREGetter, Val);
  1488. }
  1489. }
  1490. CSInfo.markDevirt();
  1491. }
  1492. bool DevirtModule::tryVirtualConstProp(
  1493. MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
  1494. WholeProgramDevirtResolution *Res, VTableSlot Slot) {
  1495. // This only works if the function returns an integer.
  1496. auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
  1497. if (!RetType)
  1498. return false;
  1499. unsigned BitWidth = RetType->getBitWidth();
  1500. if (BitWidth > 64)
  1501. return false;
  1502. // Make sure that each function is defined, does not access memory, takes at
  1503. // least one argument, does not use its first argument (which we assume is
  1504. // 'this'), and has the same return type.
  1505. //
  1506. // Note that we test whether this copy of the function is readnone, rather
  1507. // than testing function attributes, which must hold for any copy of the
  1508. // function, even a less optimized version substituted at link time. This is
  1509. // sound because the virtual constant propagation optimizations effectively
  1510. // inline all implementations of the virtual function into each call site,
  1511. // rather than using function attributes to perform local optimization.
  1512. for (VirtualCallTarget &Target : TargetsForSlot) {
  1513. if (Target.Fn->isDeclaration() ||
  1514. !computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn))
  1515. .doesNotAccessMemory() ||
  1516. Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
  1517. Target.Fn->getReturnType() != RetType)
  1518. return false;
  1519. }
  1520. for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
  1521. if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
  1522. continue;
  1523. WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
  1524. if (Res)
  1525. ResByArg = &Res->ResByArg[CSByConstantArg.first];
  1526. if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
  1527. continue;
  1528. if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
  1529. ResByArg, Slot, CSByConstantArg.first))
  1530. continue;
  1531. // Find an allocation offset in bits in all vtables associated with the
  1532. // type.
  1533. uint64_t AllocBefore =
  1534. findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
  1535. uint64_t AllocAfter =
  1536. findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
  1537. // Calculate the total amount of padding needed to store a value at both
  1538. // ends of the object.
  1539. uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
  1540. for (auto &&Target : TargetsForSlot) {
  1541. TotalPaddingBefore += std::max<int64_t>(
  1542. (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
  1543. TotalPaddingAfter += std::max<int64_t>(
  1544. (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
  1545. }
  1546. // If the amount of padding is too large, give up.
  1547. // FIXME: do something smarter here.
  1548. if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
  1549. continue;
  1550. // Calculate the offset to the value as a (possibly negative) byte offset
  1551. // and (if applicable) a bit offset, and store the values in the targets.
  1552. int64_t OffsetByte;
  1553. uint64_t OffsetBit;
  1554. if (TotalPaddingBefore <= TotalPaddingAfter)
  1555. setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
  1556. OffsetBit);
  1557. else
  1558. setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
  1559. OffsetBit);
  1560. if (RemarksEnabled || AreStatisticsEnabled())
  1561. for (auto &&Target : TargetsForSlot)
  1562. Target.WasDevirt = true;
  1563. if (CSByConstantArg.second.isExported()) {
  1564. ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
  1565. exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
  1566. ResByArg->Byte);
  1567. exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
  1568. ResByArg->Bit);
  1569. }
  1570. // Rewrite each call to a load from OffsetByte/OffsetBit.
  1571. Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
  1572. Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
  1573. applyVirtualConstProp(CSByConstantArg.second,
  1574. TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
  1575. }
  1576. return true;
  1577. }
  1578. void DevirtModule::rebuildGlobal(VTableBits &B) {
  1579. if (B.Before.Bytes.empty() && B.After.Bytes.empty())
  1580. return;
  1581. // Align the before byte array to the global's minimum alignment so that we
  1582. // don't break any alignment requirements on the global.
  1583. Align Alignment = M.getDataLayout().getValueOrABITypeAlignment(
  1584. B.GV->getAlign(), B.GV->getValueType());
  1585. B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
  1586. // Before was stored in reverse order; flip it now.
  1587. for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
  1588. std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
  1589. // Build an anonymous global containing the before bytes, followed by the
  1590. // original initializer, followed by the after bytes.
  1591. auto NewInit = ConstantStruct::getAnon(
  1592. {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
  1593. B.GV->getInitializer(),
  1594. ConstantDataArray::get(M.getContext(), B.After.Bytes)});
  1595. auto NewGV =
  1596. new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
  1597. GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
  1598. NewGV->setSection(B.GV->getSection());
  1599. NewGV->setComdat(B.GV->getComdat());
  1600. NewGV->setAlignment(B.GV->getAlign());
  1601. // Copy the original vtable's metadata to the anonymous global, adjusting
  1602. // offsets as required.
  1603. NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
  1604. // Build an alias named after the original global, pointing at the second
  1605. // element (the original initializer).
  1606. auto Alias = GlobalAlias::create(
  1607. B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
  1608. ConstantExpr::getGetElementPtr(
  1609. NewInit->getType(), NewGV,
  1610. ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
  1611. ConstantInt::get(Int32Ty, 1)}),
  1612. &M);
  1613. Alias->setVisibility(B.GV->getVisibility());
  1614. Alias->takeName(B.GV);
  1615. B.GV->replaceAllUsesWith(Alias);
  1616. B.GV->eraseFromParent();
  1617. }
  1618. bool DevirtModule::areRemarksEnabled() {
  1619. const auto &FL = M.getFunctionList();
  1620. for (const Function &Fn : FL) {
  1621. if (Fn.empty())
  1622. continue;
  1623. auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &Fn.front());
  1624. return DI.isEnabled();
  1625. }
  1626. return false;
  1627. }
  1628. void DevirtModule::scanTypeTestUsers(
  1629. Function *TypeTestFunc,
  1630. DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
  1631. // Find all virtual calls via a virtual table pointer %p under an assumption
  1632. // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
  1633. // points to a member of the type identifier %md. Group calls by (type ID,
  1634. // offset) pair (effectively the identity of the virtual function) and store
  1635. // to CallSlots.
  1636. for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) {
  1637. auto *CI = dyn_cast<CallInst>(U.getUser());
  1638. if (!CI)
  1639. continue;
  1640. // Search for virtual calls based on %p and add them to DevirtCalls.
  1641. SmallVector<DevirtCallSite, 1> DevirtCalls;
  1642. SmallVector<CallInst *, 1> Assumes;
  1643. auto &DT = LookupDomTree(*CI->getFunction());
  1644. findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
  1645. Metadata *TypeId =
  1646. cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
  1647. // If we found any, add them to CallSlots.
  1648. if (!Assumes.empty()) {
  1649. Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
  1650. for (DevirtCallSite Call : DevirtCalls)
  1651. CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr);
  1652. }
  1653. auto RemoveTypeTestAssumes = [&]() {
  1654. // We no longer need the assumes or the type test.
  1655. for (auto *Assume : Assumes)
  1656. Assume->eraseFromParent();
  1657. // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
  1658. // may use the vtable argument later.
  1659. if (CI->use_empty())
  1660. CI->eraseFromParent();
  1661. };
  1662. // At this point we could remove all type test assume sequences, as they
  1663. // were originally inserted for WPD. However, we can keep these in the
  1664. // code stream for later analysis (e.g. to help drive more efficient ICP
  1665. // sequences). They will eventually be removed by a second LowerTypeTests
  1666. // invocation that cleans them up. In order to do this correctly, the first
  1667. // LowerTypeTests invocation needs to know that they have "Unknown" type
  1668. // test resolution, so that they aren't treated as Unsat and lowered to
  1669. // False, which will break any uses on assumes. Below we remove any type
  1670. // test assumes that will not be treated as Unknown by LTT.
  1671. // The type test assumes will be treated by LTT as Unsat if the type id is
  1672. // not used on a global (in which case it has no entry in the TypeIdMap).
  1673. if (!TypeIdMap.count(TypeId))
  1674. RemoveTypeTestAssumes();
  1675. // For ThinLTO importing, we need to remove the type test assumes if this is
  1676. // an MDString type id without a corresponding TypeIdSummary. Any
  1677. // non-MDString type ids are ignored and treated as Unknown by LTT, so their
  1678. // type test assumes can be kept. If the MDString type id is missing a
  1679. // TypeIdSummary (e.g. because there was no use on a vcall, preventing the
  1680. // exporting phase of WPD from analyzing it), then it would be treated as
  1681. // Unsat by LTT and we need to remove its type test assumes here. If not
  1682. // used on a vcall we don't need them for later optimization use in any
  1683. // case.
  1684. else if (ImportSummary && isa<MDString>(TypeId)) {
  1685. const TypeIdSummary *TidSummary =
  1686. ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString());
  1687. if (!TidSummary)
  1688. RemoveTypeTestAssumes();
  1689. else
  1690. // If one was created it should not be Unsat, because if we reached here
  1691. // the type id was used on a global.
  1692. assert(TidSummary->TTRes.TheKind != TypeTestResolution::Unsat);
  1693. }
  1694. }
  1695. }
  1696. void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
  1697. Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
  1698. for (Use &U : llvm::make_early_inc_range(TypeCheckedLoadFunc->uses())) {
  1699. auto *CI = dyn_cast<CallInst>(U.getUser());
  1700. if (!CI)
  1701. continue;
  1702. Value *Ptr = CI->getArgOperand(0);
  1703. Value *Offset = CI->getArgOperand(1);
  1704. Value *TypeIdValue = CI->getArgOperand(2);
  1705. Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
  1706. SmallVector<DevirtCallSite, 1> DevirtCalls;
  1707. SmallVector<Instruction *, 1> LoadedPtrs;
  1708. SmallVector<Instruction *, 1> Preds;
  1709. bool HasNonCallUses = false;
  1710. auto &DT = LookupDomTree(*CI->getFunction());
  1711. findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
  1712. HasNonCallUses, CI, DT);
  1713. // Start by generating "pessimistic" code that explicitly loads the function
  1714. // pointer from the vtable and performs the type check. If possible, we will
  1715. // eliminate the load and the type check later.
  1716. // If possible, only generate the load at the point where it is used.
  1717. // This helps avoid unnecessary spills.
  1718. IRBuilder<> LoadB(
  1719. (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
  1720. Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
  1721. Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
  1722. Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
  1723. for (Instruction *LoadedPtr : LoadedPtrs) {
  1724. LoadedPtr->replaceAllUsesWith(LoadedValue);
  1725. LoadedPtr->eraseFromParent();
  1726. }
  1727. // Likewise for the type test.
  1728. IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
  1729. CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
  1730. for (Instruction *Pred : Preds) {
  1731. Pred->replaceAllUsesWith(TypeTestCall);
  1732. Pred->eraseFromParent();
  1733. }
  1734. // We have already erased any extractvalue instructions that refer to the
  1735. // intrinsic call, but the intrinsic may have other non-extractvalue uses
  1736. // (although this is unlikely). In that case, explicitly build a pair and
  1737. // RAUW it.
  1738. if (!CI->use_empty()) {
  1739. Value *Pair = PoisonValue::get(CI->getType());
  1740. IRBuilder<> B(CI);
  1741. Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
  1742. Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
  1743. CI->replaceAllUsesWith(Pair);
  1744. }
  1745. // The number of unsafe uses is initially the number of uses.
  1746. auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
  1747. NumUnsafeUses = DevirtCalls.size();
  1748. // If the function pointer has a non-call user, we cannot eliminate the type
  1749. // check, as one of those users may eventually call the pointer. Increment
  1750. // the unsafe use count to make sure it cannot reach zero.
  1751. if (HasNonCallUses)
  1752. ++NumUnsafeUses;
  1753. for (DevirtCallSite Call : DevirtCalls) {
  1754. CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB,
  1755. &NumUnsafeUses);
  1756. }
  1757. CI->eraseFromParent();
  1758. }
  1759. }
  1760. void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
  1761. auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
  1762. if (!TypeId)
  1763. return;
  1764. const TypeIdSummary *TidSummary =
  1765. ImportSummary->getTypeIdSummary(TypeId->getString());
  1766. if (!TidSummary)
  1767. return;
  1768. auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
  1769. if (ResI == TidSummary->WPDRes.end())
  1770. return;
  1771. const WholeProgramDevirtResolution &Res = ResI->second;
  1772. if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
  1773. assert(!Res.SingleImplName.empty());
  1774. // The type of the function in the declaration is irrelevant because every
  1775. // call site will cast it to the correct type.
  1776. Constant *SingleImpl =
  1777. cast<Constant>(M.getOrInsertFunction(Res.SingleImplName,
  1778. Type::getVoidTy(M.getContext()))
  1779. .getCallee());
  1780. // This is the import phase so we should not be exporting anything.
  1781. bool IsExported = false;
  1782. applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
  1783. assert(!IsExported);
  1784. }
  1785. for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
  1786. auto I = Res.ResByArg.find(CSByConstantArg.first);
  1787. if (I == Res.ResByArg.end())
  1788. continue;
  1789. auto &ResByArg = I->second;
  1790. // FIXME: We should figure out what to do about the "function name" argument
  1791. // to the apply* functions, as the function names are unavailable during the
  1792. // importing phase. For now we just pass the empty string. This does not
  1793. // impact correctness because the function names are just used for remarks.
  1794. switch (ResByArg.TheKind) {
  1795. case WholeProgramDevirtResolution::ByArg::UniformRetVal:
  1796. applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
  1797. break;
  1798. case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
  1799. Constant *UniqueMemberAddr =
  1800. importGlobal(Slot, CSByConstantArg.first, "unique_member");
  1801. applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
  1802. UniqueMemberAddr);
  1803. break;
  1804. }
  1805. case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
  1806. Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
  1807. Int32Ty, ResByArg.Byte);
  1808. Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
  1809. ResByArg.Bit);
  1810. applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
  1811. break;
  1812. }
  1813. default:
  1814. break;
  1815. }
  1816. }
  1817. if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
  1818. // The type of the function is irrelevant, because it's bitcast at calls
  1819. // anyhow.
  1820. Constant *JT = cast<Constant>(
  1821. M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
  1822. Type::getVoidTy(M.getContext()))
  1823. .getCallee());
  1824. bool IsExported = false;
  1825. applyICallBranchFunnel(SlotInfo, JT, IsExported);
  1826. assert(!IsExported);
  1827. }
  1828. }
  1829. void DevirtModule::removeRedundantTypeTests() {
  1830. auto True = ConstantInt::getTrue(M.getContext());
  1831. for (auto &&U : NumUnsafeUsesForTypeTest) {
  1832. if (U.second == 0) {
  1833. U.first->replaceAllUsesWith(True);
  1834. U.first->eraseFromParent();
  1835. }
  1836. }
  1837. }
  1838. ValueInfo
  1839. DevirtModule::lookUpFunctionValueInfo(Function *TheFn,
  1840. ModuleSummaryIndex *ExportSummary) {
  1841. assert((ExportSummary != nullptr) &&
  1842. "Caller guarantees ExportSummary is not nullptr");
  1843. const auto TheFnGUID = TheFn->getGUID();
  1844. const auto TheFnGUIDWithExportedName = GlobalValue::getGUID(TheFn->getName());
  1845. // Look up ValueInfo with the GUID in the current linkage.
  1846. ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFnGUID);
  1847. // If no entry is found and GUID is different from GUID computed using
  1848. // exported name, look up ValueInfo with the exported name unconditionally.
  1849. // This is a fallback.
  1850. //
  1851. // The reason to have a fallback:
  1852. // 1. LTO could enable global value internalization via
  1853. // `enable-lto-internalization`.
  1854. // 2. The GUID in ExportedSummary is computed using exported name.
  1855. if ((!TheFnVI) && (TheFnGUID != TheFnGUIDWithExportedName)) {
  1856. TheFnVI = ExportSummary->getValueInfo(TheFnGUIDWithExportedName);
  1857. }
  1858. return TheFnVI;
  1859. }
  1860. bool DevirtModule::mustBeUnreachableFunction(
  1861. Function *const F, ModuleSummaryIndex *ExportSummary) {
  1862. // First, learn unreachability by analyzing function IR.
  1863. if (!F->isDeclaration()) {
  1864. // A function must be unreachable if its entry block ends with an
  1865. // 'unreachable'.
  1866. return isa<UnreachableInst>(F->getEntryBlock().getTerminator());
  1867. }
  1868. // Learn unreachability from ExportSummary if ExportSummary is present.
  1869. return ExportSummary &&
  1870. ::mustBeUnreachableFunction(
  1871. DevirtModule::lookUpFunctionValueInfo(F, ExportSummary));
  1872. }
  1873. bool DevirtModule::run() {
  1874. // If only some of the modules were split, we cannot correctly perform
  1875. // this transformation. We already checked for the presense of type tests
  1876. // with partially split modules during the thin link, and would have emitted
  1877. // an error if any were found, so here we can simply return.
  1878. if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
  1879. (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
  1880. return false;
  1881. Function *TypeTestFunc =
  1882. M.getFunction(Intrinsic::getName(Intrinsic::type_test));
  1883. Function *TypeCheckedLoadFunc =
  1884. M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
  1885. Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
  1886. // Normally if there are no users of the devirtualization intrinsics in the
  1887. // module, this pass has nothing to do. But if we are exporting, we also need
  1888. // to handle any users that appear only in the function summaries.
  1889. if (!ExportSummary &&
  1890. (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
  1891. AssumeFunc->use_empty()) &&
  1892. (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
  1893. return false;
  1894. // Rebuild type metadata into a map for easy lookup.
  1895. std::vector<VTableBits> Bits;
  1896. DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
  1897. buildTypeIdentifierMap(Bits, TypeIdMap);
  1898. if (TypeTestFunc && AssumeFunc)
  1899. scanTypeTestUsers(TypeTestFunc, TypeIdMap);
  1900. if (TypeCheckedLoadFunc)
  1901. scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
  1902. if (ImportSummary) {
  1903. for (auto &S : CallSlots)
  1904. importResolution(S.first, S.second);
  1905. removeRedundantTypeTests();
  1906. // We have lowered or deleted the type intrinsics, so we will no longer have
  1907. // enough information to reason about the liveness of virtual function
  1908. // pointers in GlobalDCE.
  1909. for (GlobalVariable &GV : M.globals())
  1910. GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
  1911. // The rest of the code is only necessary when exporting or during regular
  1912. // LTO, so we are done.
  1913. return true;
  1914. }
  1915. if (TypeIdMap.empty())
  1916. return true;
  1917. // Collect information from summary about which calls to try to devirtualize.
  1918. if (ExportSummary) {
  1919. DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
  1920. for (auto &P : TypeIdMap) {
  1921. if (auto *TypeId = dyn_cast<MDString>(P.first))
  1922. MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
  1923. TypeId);
  1924. }
  1925. for (auto &P : *ExportSummary) {
  1926. for (auto &S : P.second.SummaryList) {
  1927. auto *FS = dyn_cast<FunctionSummary>(S.get());
  1928. if (!FS)
  1929. continue;
  1930. // FIXME: Only add live functions.
  1931. for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
  1932. for (Metadata *MD : MetadataByGUID[VF.GUID]) {
  1933. CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
  1934. }
  1935. }
  1936. for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
  1937. for (Metadata *MD : MetadataByGUID[VF.GUID]) {
  1938. CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
  1939. }
  1940. }
  1941. for (const FunctionSummary::ConstVCall &VC :
  1942. FS->type_test_assume_const_vcalls()) {
  1943. for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
  1944. CallSlots[{MD, VC.VFunc.Offset}]
  1945. .ConstCSInfo[VC.Args]
  1946. .addSummaryTypeTestAssumeUser(FS);
  1947. }
  1948. }
  1949. for (const FunctionSummary::ConstVCall &VC :
  1950. FS->type_checked_load_const_vcalls()) {
  1951. for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
  1952. CallSlots[{MD, VC.VFunc.Offset}]
  1953. .ConstCSInfo[VC.Args]
  1954. .addSummaryTypeCheckedLoadUser(FS);
  1955. }
  1956. }
  1957. }
  1958. }
  1959. }
  1960. // For each (type, offset) pair:
  1961. bool DidVirtualConstProp = false;
  1962. std::map<std::string, Function*> DevirtTargets;
  1963. for (auto &S : CallSlots) {
  1964. // Search each of the members of the type identifier for the virtual
  1965. // function implementation at offset S.first.ByteOffset, and add to
  1966. // TargetsForSlot.
  1967. std::vector<VirtualCallTarget> TargetsForSlot;
  1968. WholeProgramDevirtResolution *Res = nullptr;
  1969. const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID];
  1970. if (ExportSummary && isa<MDString>(S.first.TypeID) &&
  1971. TypeMemberInfos.size())
  1972. // For any type id used on a global's type metadata, create the type id
  1973. // summary resolution regardless of whether we can devirtualize, so that
  1974. // lower type tests knows the type id is not Unsat. If it was not used on
  1975. // a global's type metadata, the TypeIdMap entry set will be empty, and
  1976. // we don't want to create an entry (with the default Unknown type
  1977. // resolution), which can prevent detection of the Unsat.
  1978. Res = &ExportSummary
  1979. ->getOrInsertTypeIdSummary(
  1980. cast<MDString>(S.first.TypeID)->getString())
  1981. .WPDRes[S.first.ByteOffset];
  1982. if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos,
  1983. S.first.ByteOffset, ExportSummary)) {
  1984. if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) {
  1985. DidVirtualConstProp |=
  1986. tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
  1987. tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
  1988. }
  1989. // Collect functions devirtualized at least for one call site for stats.
  1990. if (RemarksEnabled || AreStatisticsEnabled())
  1991. for (const auto &T : TargetsForSlot)
  1992. if (T.WasDevirt)
  1993. DevirtTargets[std::string(T.Fn->getName())] = T.Fn;
  1994. }
  1995. // CFI-specific: if we are exporting and any llvm.type.checked.load
  1996. // intrinsics were *not* devirtualized, we need to add the resulting
  1997. // llvm.type.test intrinsics to the function summaries so that the
  1998. // LowerTypeTests pass will export them.
  1999. if (ExportSummary && isa<MDString>(S.first.TypeID)) {
  2000. auto GUID =
  2001. GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
  2002. for (auto *FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
  2003. FS->addTypeTest(GUID);
  2004. for (auto &CCS : S.second.ConstCSInfo)
  2005. for (auto *FS : CCS.second.SummaryTypeCheckedLoadUsers)
  2006. FS->addTypeTest(GUID);
  2007. }
  2008. }
  2009. if (RemarksEnabled) {
  2010. // Generate remarks for each devirtualized function.
  2011. for (const auto &DT : DevirtTargets) {
  2012. Function *F = DT.second;
  2013. using namespace ore;
  2014. OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
  2015. << "devirtualized "
  2016. << NV("FunctionName", DT.first));
  2017. }
  2018. }
  2019. NumDevirtTargets += DevirtTargets.size();
  2020. removeRedundantTypeTests();
  2021. // Rebuild each global we touched as part of virtual constant propagation to
  2022. // include the before and after bytes.
  2023. if (DidVirtualConstProp)
  2024. for (VTableBits &B : Bits)
  2025. rebuildGlobal(B);
  2026. // We have lowered or deleted the type intrinsics, so we will no longer have
  2027. // enough information to reason about the liveness of virtual function
  2028. // pointers in GlobalDCE.
  2029. for (GlobalVariable &GV : M.globals())
  2030. GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
  2031. return true;
  2032. }
  2033. void DevirtIndex::run() {
  2034. if (ExportSummary.typeIdCompatibleVtableMap().empty())
  2035. return;
  2036. DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
  2037. for (const auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
  2038. NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first);
  2039. // Create the type id summary resolution regardlness of whether we can
  2040. // devirtualize, so that lower type tests knows the type id is used on
  2041. // a global and not Unsat. We do this here rather than in the loop over the
  2042. // CallSlots, since that handling will only see type tests that directly
  2043. // feed assumes, and we would miss any that aren't currently handled by WPD
  2044. // (such as type tests that feed assumes via phis).
  2045. ExportSummary.getOrInsertTypeIdSummary(P.first);
  2046. }
  2047. // Collect information from summary about which calls to try to devirtualize.
  2048. for (auto &P : ExportSummary) {
  2049. for (auto &S : P.second.SummaryList) {
  2050. auto *FS = dyn_cast<FunctionSummary>(S.get());
  2051. if (!FS)
  2052. continue;
  2053. // FIXME: Only add live functions.
  2054. for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
  2055. for (StringRef Name : NameByGUID[VF.GUID]) {
  2056. CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
  2057. }
  2058. }
  2059. for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
  2060. for (StringRef Name : NameByGUID[VF.GUID]) {
  2061. CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
  2062. }
  2063. }
  2064. for (const FunctionSummary::ConstVCall &VC :
  2065. FS->type_test_assume_const_vcalls()) {
  2066. for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
  2067. CallSlots[{Name, VC.VFunc.Offset}]
  2068. .ConstCSInfo[VC.Args]
  2069. .addSummaryTypeTestAssumeUser(FS);
  2070. }
  2071. }
  2072. for (const FunctionSummary::ConstVCall &VC :
  2073. FS->type_checked_load_const_vcalls()) {
  2074. for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
  2075. CallSlots[{Name, VC.VFunc.Offset}]
  2076. .ConstCSInfo[VC.Args]
  2077. .addSummaryTypeCheckedLoadUser(FS);
  2078. }
  2079. }
  2080. }
  2081. }
  2082. std::set<ValueInfo> DevirtTargets;
  2083. // For each (type, offset) pair:
  2084. for (auto &S : CallSlots) {
  2085. // Search each of the members of the type identifier for the virtual
  2086. // function implementation at offset S.first.ByteOffset, and add to
  2087. // TargetsForSlot.
  2088. std::vector<ValueInfo> TargetsForSlot;
  2089. auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
  2090. assert(TidSummary);
  2091. // The type id summary would have been created while building the NameByGUID
  2092. // map earlier.
  2093. WholeProgramDevirtResolution *Res =
  2094. &ExportSummary.getTypeIdSummary(S.first.TypeID)
  2095. ->WPDRes[S.first.ByteOffset];
  2096. if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
  2097. S.first.ByteOffset)) {
  2098. if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
  2099. DevirtTargets))
  2100. continue;
  2101. }
  2102. }
  2103. // Optionally have the thin link print message for each devirtualized
  2104. // function.
  2105. if (PrintSummaryDevirt)
  2106. for (const auto &DT : DevirtTargets)
  2107. errs() << "Devirtualized call to " << DT << "\n";
  2108. NumDevirtTargets += DevirtTargets.size();
  2109. }