GlobalOpt.cpp 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  1. //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
  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 transforms simple global variables that never have their address
  10. // taken. If obviously true, it marks read/write globals as constant, deletes
  11. // variables only stored to, etc.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/IPO/GlobalOpt.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/ADT/iterator_range.h"
  22. #include "llvm/Analysis/BlockFrequencyInfo.h"
  23. #include "llvm/Analysis/ConstantFolding.h"
  24. #include "llvm/Analysis/MemoryBuiltins.h"
  25. #include "llvm/Analysis/TargetLibraryInfo.h"
  26. #include "llvm/Analysis/TargetTransformInfo.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/BinaryFormat/Dwarf.h"
  29. #include "llvm/IR/Attributes.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/CallingConv.h"
  32. #include "llvm/IR/Constant.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/DebugInfoMetadata.h"
  36. #include "llvm/IR/DerivedTypes.h"
  37. #include "llvm/IR/Dominators.h"
  38. #include "llvm/IR/Function.h"
  39. #include "llvm/IR/GetElementPtrTypeIterator.h"
  40. #include "llvm/IR/GlobalAlias.h"
  41. #include "llvm/IR/GlobalValue.h"
  42. #include "llvm/IR/GlobalVariable.h"
  43. #include "llvm/IR/IRBuilder.h"
  44. #include "llvm/IR/InstrTypes.h"
  45. #include "llvm/IR/Instruction.h"
  46. #include "llvm/IR/Instructions.h"
  47. #include "llvm/IR/IntrinsicInst.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/IR/Operator.h"
  50. #include "llvm/IR/Type.h"
  51. #include "llvm/IR/Use.h"
  52. #include "llvm/IR/User.h"
  53. #include "llvm/IR/Value.h"
  54. #include "llvm/IR/ValueHandle.h"
  55. #include "llvm/InitializePasses.h"
  56. #include "llvm/Pass.h"
  57. #include "llvm/Support/AtomicOrdering.h"
  58. #include "llvm/Support/Casting.h"
  59. #include "llvm/Support/CommandLine.h"
  60. #include "llvm/Support/Debug.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/MathExtras.h"
  63. #include "llvm/Support/raw_ostream.h"
  64. #include "llvm/Transforms/IPO.h"
  65. #include "llvm/Transforms/Utils/CtorUtils.h"
  66. #include "llvm/Transforms/Utils/Evaluator.h"
  67. #include "llvm/Transforms/Utils/GlobalStatus.h"
  68. #include "llvm/Transforms/Utils/Local.h"
  69. #include <cassert>
  70. #include <cstdint>
  71. #include <utility>
  72. #include <vector>
  73. using namespace llvm;
  74. #define DEBUG_TYPE "globalopt"
  75. STATISTIC(NumMarked , "Number of globals marked constant");
  76. STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
  77. STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
  78. STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
  79. STATISTIC(NumDeleted , "Number of globals deleted");
  80. STATISTIC(NumGlobUses , "Number of global uses devirtualized");
  81. STATISTIC(NumLocalized , "Number of globals localized");
  82. STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
  83. STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
  84. STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
  85. STATISTIC(NumNestRemoved , "Number of nest attributes removed");
  86. STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
  87. STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
  88. STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
  89. STATISTIC(NumInternalFunc, "Number of internal functions");
  90. STATISTIC(NumColdCC, "Number of functions marked coldcc");
  91. static cl::opt<bool>
  92. EnableColdCCStressTest("enable-coldcc-stress-test",
  93. cl::desc("Enable stress test of coldcc by adding "
  94. "calling conv to all internal functions."),
  95. cl::init(false), cl::Hidden);
  96. static cl::opt<int> ColdCCRelFreq(
  97. "coldcc-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
  98. cl::desc(
  99. "Maximum block frequency, expressed as a percentage of caller's "
  100. "entry frequency, for a call site to be considered cold for enabling"
  101. "coldcc"));
  102. /// Is this global variable possibly used by a leak checker as a root? If so,
  103. /// we might not really want to eliminate the stores to it.
  104. static bool isLeakCheckerRoot(GlobalVariable *GV) {
  105. // A global variable is a root if it is a pointer, or could plausibly contain
  106. // a pointer. There are two challenges; one is that we could have a struct
  107. // the has an inner member which is a pointer. We recurse through the type to
  108. // detect these (up to a point). The other is that we may actually be a union
  109. // of a pointer and another type, and so our LLVM type is an integer which
  110. // gets converted into a pointer, or our type is an [i8 x #] with a pointer
  111. // potentially contained here.
  112. if (GV->hasPrivateLinkage())
  113. return false;
  114. SmallVector<Type *, 4> Types;
  115. Types.push_back(GV->getValueType());
  116. unsigned Limit = 20;
  117. do {
  118. Type *Ty = Types.pop_back_val();
  119. switch (Ty->getTypeID()) {
  120. default: break;
  121. case Type::PointerTyID:
  122. return true;
  123. case Type::FixedVectorTyID:
  124. case Type::ScalableVectorTyID:
  125. if (cast<VectorType>(Ty)->getElementType()->isPointerTy())
  126. return true;
  127. break;
  128. case Type::ArrayTyID:
  129. Types.push_back(cast<ArrayType>(Ty)->getElementType());
  130. break;
  131. case Type::StructTyID: {
  132. StructType *STy = cast<StructType>(Ty);
  133. if (STy->isOpaque()) return true;
  134. for (StructType::element_iterator I = STy->element_begin(),
  135. E = STy->element_end(); I != E; ++I) {
  136. Type *InnerTy = *I;
  137. if (isa<PointerType>(InnerTy)) return true;
  138. if (isa<StructType>(InnerTy) || isa<ArrayType>(InnerTy) ||
  139. isa<VectorType>(InnerTy))
  140. Types.push_back(InnerTy);
  141. }
  142. break;
  143. }
  144. }
  145. if (--Limit == 0) return true;
  146. } while (!Types.empty());
  147. return false;
  148. }
  149. /// Given a value that is stored to a global but never read, determine whether
  150. /// it's safe to remove the store and the chain of computation that feeds the
  151. /// store.
  152. static bool IsSafeComputationToRemove(
  153. Value *V, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  154. do {
  155. if (isa<Constant>(V))
  156. return true;
  157. if (!V->hasOneUse())
  158. return false;
  159. if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
  160. isa<GlobalValue>(V))
  161. return false;
  162. if (isAllocationFn(V, GetTLI))
  163. return true;
  164. Instruction *I = cast<Instruction>(V);
  165. if (I->mayHaveSideEffects())
  166. return false;
  167. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
  168. if (!GEP->hasAllConstantIndices())
  169. return false;
  170. } else if (I->getNumOperands() != 1) {
  171. return false;
  172. }
  173. V = I->getOperand(0);
  174. } while (true);
  175. }
  176. /// This GV is a pointer root. Loop over all users of the global and clean up
  177. /// any that obviously don't assign the global a value that isn't dynamically
  178. /// allocated.
  179. static bool
  180. CleanupPointerRootUsers(GlobalVariable *GV,
  181. function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  182. // A brief explanation of leak checkers. The goal is to find bugs where
  183. // pointers are forgotten, causing an accumulating growth in memory
  184. // usage over time. The common strategy for leak checkers is to explicitly
  185. // allow the memory pointed to by globals at exit. This is popular because it
  186. // also solves another problem where the main thread of a C++ program may shut
  187. // down before other threads that are still expecting to use those globals. To
  188. // handle that case, we expect the program may create a singleton and never
  189. // destroy it.
  190. bool Changed = false;
  191. // If Dead[n].first is the only use of a malloc result, we can delete its
  192. // chain of computation and the store to the global in Dead[n].second.
  193. SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
  194. // Constants can't be pointers to dynamically allocated memory.
  195. for (User *U : llvm::make_early_inc_range(GV->users())) {
  196. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  197. Value *V = SI->getValueOperand();
  198. if (isa<Constant>(V)) {
  199. Changed = true;
  200. SI->eraseFromParent();
  201. } else if (Instruction *I = dyn_cast<Instruction>(V)) {
  202. if (I->hasOneUse())
  203. Dead.push_back(std::make_pair(I, SI));
  204. }
  205. } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
  206. if (isa<Constant>(MSI->getValue())) {
  207. Changed = true;
  208. MSI->eraseFromParent();
  209. } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
  210. if (I->hasOneUse())
  211. Dead.push_back(std::make_pair(I, MSI));
  212. }
  213. } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
  214. GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
  215. if (MemSrc && MemSrc->isConstant()) {
  216. Changed = true;
  217. MTI->eraseFromParent();
  218. } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
  219. if (I->hasOneUse())
  220. Dead.push_back(std::make_pair(I, MTI));
  221. }
  222. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
  223. if (CE->use_empty()) {
  224. CE->destroyConstant();
  225. Changed = true;
  226. }
  227. } else if (Constant *C = dyn_cast<Constant>(U)) {
  228. if (isSafeToDestroyConstant(C)) {
  229. C->destroyConstant();
  230. // This could have invalidated UI, start over from scratch.
  231. Dead.clear();
  232. CleanupPointerRootUsers(GV, GetTLI);
  233. return true;
  234. }
  235. }
  236. }
  237. for (int i = 0, e = Dead.size(); i != e; ++i) {
  238. if (IsSafeComputationToRemove(Dead[i].first, GetTLI)) {
  239. Dead[i].second->eraseFromParent();
  240. Instruction *I = Dead[i].first;
  241. do {
  242. if (isAllocationFn(I, GetTLI))
  243. break;
  244. Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
  245. if (!J)
  246. break;
  247. I->eraseFromParent();
  248. I = J;
  249. } while (true);
  250. I->eraseFromParent();
  251. Changed = true;
  252. }
  253. }
  254. return Changed;
  255. }
  256. /// We just marked GV constant. Loop over all users of the global, cleaning up
  257. /// the obvious ones. This is largely just a quick scan over the use list to
  258. /// clean up the easy and obvious cruft. This returns true if it made a change.
  259. static bool CleanupConstantGlobalUsers(GlobalVariable *GV,
  260. const DataLayout &DL) {
  261. Constant *Init = GV->getInitializer();
  262. SmallVector<User *, 8> WorkList(GV->users());
  263. SmallPtrSet<User *, 8> Visited;
  264. bool Changed = false;
  265. SmallVector<WeakTrackingVH> MaybeDeadInsts;
  266. auto EraseFromParent = [&](Instruction *I) {
  267. for (Value *Op : I->operands())
  268. if (auto *OpI = dyn_cast<Instruction>(Op))
  269. MaybeDeadInsts.push_back(OpI);
  270. I->eraseFromParent();
  271. Changed = true;
  272. };
  273. while (!WorkList.empty()) {
  274. User *U = WorkList.pop_back_val();
  275. if (!Visited.insert(U).second)
  276. continue;
  277. if (auto *BO = dyn_cast<BitCastOperator>(U))
  278. append_range(WorkList, BO->users());
  279. if (auto *ASC = dyn_cast<AddrSpaceCastOperator>(U))
  280. append_range(WorkList, ASC->users());
  281. else if (auto *GEP = dyn_cast<GEPOperator>(U))
  282. append_range(WorkList, GEP->users());
  283. else if (auto *LI = dyn_cast<LoadInst>(U)) {
  284. // A load from a uniform value is always the same, regardless of any
  285. // applied offset.
  286. Type *Ty = LI->getType();
  287. if (Constant *Res = ConstantFoldLoadFromUniformValue(Init, Ty)) {
  288. LI->replaceAllUsesWith(Res);
  289. EraseFromParent(LI);
  290. continue;
  291. }
  292. Value *PtrOp = LI->getPointerOperand();
  293. APInt Offset(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
  294. PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
  295. DL, Offset, /* AllowNonInbounds */ true);
  296. if (PtrOp == GV) {
  297. if (auto *Value = ConstantFoldLoadFromConst(Init, Ty, Offset, DL)) {
  298. LI->replaceAllUsesWith(Value);
  299. EraseFromParent(LI);
  300. }
  301. }
  302. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  303. // Store must be unreachable or storing Init into the global.
  304. EraseFromParent(SI);
  305. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
  306. if (getUnderlyingObject(MI->getRawDest()) == GV)
  307. EraseFromParent(MI);
  308. }
  309. }
  310. Changed |=
  311. RecursivelyDeleteTriviallyDeadInstructionsPermissive(MaybeDeadInsts);
  312. GV->removeDeadConstantUsers();
  313. return Changed;
  314. }
  315. /// Look at all uses of the global and determine which (offset, type) pairs it
  316. /// can be split into.
  317. static bool collectSRATypes(DenseMap<uint64_t, Type *> &Types, GlobalValue *GV,
  318. const DataLayout &DL) {
  319. SmallVector<Use *, 16> Worklist;
  320. SmallPtrSet<Use *, 16> Visited;
  321. auto AppendUses = [&](Value *V) {
  322. for (Use &U : V->uses())
  323. if (Visited.insert(&U).second)
  324. Worklist.push_back(&U);
  325. };
  326. AppendUses(GV);
  327. while (!Worklist.empty()) {
  328. Use *U = Worklist.pop_back_val();
  329. User *V = U->getUser();
  330. auto *GEP = dyn_cast<GEPOperator>(V);
  331. if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) ||
  332. (GEP && GEP->hasAllConstantIndices())) {
  333. AppendUses(V);
  334. continue;
  335. }
  336. if (Value *Ptr = getLoadStorePointerOperand(V)) {
  337. // This is storing the global address into somewhere, not storing into
  338. // the global.
  339. if (isa<StoreInst>(V) && U->getOperandNo() == 0)
  340. return false;
  341. APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
  342. Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
  343. /* AllowNonInbounds */ true);
  344. if (Ptr != GV || Offset.getActiveBits() >= 64)
  345. return false;
  346. // TODO: We currently require that all accesses at a given offset must
  347. // use the same type. This could be relaxed.
  348. Type *Ty = getLoadStoreType(V);
  349. auto It = Types.try_emplace(Offset.getZExtValue(), Ty).first;
  350. if (Ty != It->second)
  351. return false;
  352. continue;
  353. }
  354. // Ignore dead constant users.
  355. if (auto *C = dyn_cast<Constant>(V)) {
  356. if (!isSafeToDestroyConstant(C))
  357. return false;
  358. continue;
  359. }
  360. // Unknown user.
  361. return false;
  362. }
  363. return true;
  364. }
  365. /// Copy over the debug info for a variable to its SRA replacements.
  366. static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV,
  367. uint64_t FragmentOffsetInBits,
  368. uint64_t FragmentSizeInBits,
  369. uint64_t VarSize) {
  370. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  371. GV->getDebugInfo(GVs);
  372. for (auto *GVE : GVs) {
  373. DIVariable *Var = GVE->getVariable();
  374. DIExpression *Expr = GVE->getExpression();
  375. // If the FragmentSize is smaller than the variable,
  376. // emit a fragment expression.
  377. if (FragmentSizeInBits < VarSize) {
  378. if (auto E = DIExpression::createFragmentExpression(
  379. Expr, FragmentOffsetInBits, FragmentSizeInBits))
  380. Expr = *E;
  381. else
  382. return;
  383. }
  384. auto *NGVE = DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr);
  385. NGV->addDebugInfo(NGVE);
  386. }
  387. }
  388. /// Perform scalar replacement of aggregates on the specified global variable.
  389. /// This opens the door for other optimizations by exposing the behavior of the
  390. /// program in a more fine-grained way. We have determined that this
  391. /// transformation is safe already. We return the first global variable we
  392. /// insert so that the caller can reprocess it.
  393. static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
  394. assert(GV->hasLocalLinkage());
  395. // Collect types to split into.
  396. DenseMap<uint64_t, Type *> Types;
  397. if (!collectSRATypes(Types, GV, DL) || Types.empty())
  398. return nullptr;
  399. // Make sure we don't SRA back to the same type.
  400. if (Types.size() == 1 && Types.begin()->second == GV->getValueType())
  401. return nullptr;
  402. // Don't perform SRA if we would have to split into many globals.
  403. if (Types.size() > 16)
  404. return nullptr;
  405. // Sort by offset.
  406. SmallVector<std::pair<uint64_t, Type *>, 16> TypesVector;
  407. append_range(TypesVector, Types);
  408. sort(TypesVector,
  409. [](const auto &A, const auto &B) { return A.first < B.first; });
  410. // Check that the types are non-overlapping.
  411. uint64_t Offset = 0;
  412. for (const auto &Pair : TypesVector) {
  413. // Overlaps with previous type.
  414. if (Pair.first < Offset)
  415. return nullptr;
  416. Offset = Pair.first + DL.getTypeAllocSize(Pair.second);
  417. }
  418. // Some accesses go beyond the end of the global, don't bother.
  419. if (Offset > DL.getTypeAllocSize(GV->getValueType()))
  420. return nullptr;
  421. // Collect initializers for new globals.
  422. Constant *OrigInit = GV->getInitializer();
  423. DenseMap<uint64_t, Constant *> Initializers;
  424. for (const auto &Pair : Types) {
  425. Constant *NewInit = ConstantFoldLoadFromConst(OrigInit, Pair.second,
  426. APInt(64, Pair.first), DL);
  427. if (!NewInit) {
  428. LLVM_DEBUG(dbgs() << "Global SRA: Failed to evaluate initializer of "
  429. << *GV << " with type " << *Pair.second << " at offset "
  430. << Pair.first << "\n");
  431. return nullptr;
  432. }
  433. Initializers.insert({Pair.first, NewInit});
  434. }
  435. LLVM_DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
  436. // Get the alignment of the global, either explicit or target-specific.
  437. Align StartAlignment =
  438. DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
  439. uint64_t VarSize = DL.getTypeSizeInBits(GV->getValueType());
  440. // Create replacement globals.
  441. DenseMap<uint64_t, GlobalVariable *> NewGlobals;
  442. unsigned NameSuffix = 0;
  443. for (auto &Pair : TypesVector) {
  444. uint64_t Offset = Pair.first;
  445. Type *Ty = Pair.second;
  446. GlobalVariable *NGV = new GlobalVariable(
  447. *GV->getParent(), Ty, false, GlobalVariable::InternalLinkage,
  448. Initializers[Offset], GV->getName() + "." + Twine(NameSuffix++), GV,
  449. GV->getThreadLocalMode(), GV->getAddressSpace());
  450. NGV->copyAttributesFrom(GV);
  451. NewGlobals.insert({Offset, NGV});
  452. // Calculate the known alignment of the field. If the original aggregate
  453. // had 256 byte alignment for example, something might depend on that:
  454. // propagate info to each field.
  455. Align NewAlign = commonAlignment(StartAlignment, Offset);
  456. if (NewAlign > DL.getABITypeAlign(Ty))
  457. NGV->setAlignment(NewAlign);
  458. // Copy over the debug info for the variable.
  459. transferSRADebugInfo(GV, NGV, Offset * 8, DL.getTypeAllocSizeInBits(Ty),
  460. VarSize);
  461. }
  462. // Replace uses of the original global with uses of the new global.
  463. SmallVector<Value *, 16> Worklist;
  464. SmallPtrSet<Value *, 16> Visited;
  465. SmallVector<WeakTrackingVH, 16> DeadInsts;
  466. auto AppendUsers = [&](Value *V) {
  467. for (User *U : V->users())
  468. if (Visited.insert(U).second)
  469. Worklist.push_back(U);
  470. };
  471. AppendUsers(GV);
  472. while (!Worklist.empty()) {
  473. Value *V = Worklist.pop_back_val();
  474. if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) ||
  475. isa<GEPOperator>(V)) {
  476. AppendUsers(V);
  477. if (isa<Instruction>(V))
  478. DeadInsts.push_back(V);
  479. continue;
  480. }
  481. if (Value *Ptr = getLoadStorePointerOperand(V)) {
  482. APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
  483. Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset,
  484. /* AllowNonInbounds */ true);
  485. assert(Ptr == GV && "Load/store must be from/to global");
  486. GlobalVariable *NGV = NewGlobals[Offset.getZExtValue()];
  487. assert(NGV && "Must have replacement global for this offset");
  488. // Update the pointer operand and recalculate alignment.
  489. Align PrefAlign = DL.getPrefTypeAlign(getLoadStoreType(V));
  490. Align NewAlign =
  491. getOrEnforceKnownAlignment(NGV, PrefAlign, DL, cast<Instruction>(V));
  492. if (auto *LI = dyn_cast<LoadInst>(V)) {
  493. LI->setOperand(0, NGV);
  494. LI->setAlignment(NewAlign);
  495. } else {
  496. auto *SI = cast<StoreInst>(V);
  497. SI->setOperand(1, NGV);
  498. SI->setAlignment(NewAlign);
  499. }
  500. continue;
  501. }
  502. assert(isa<Constant>(V) && isSafeToDestroyConstant(cast<Constant>(V)) &&
  503. "Other users can only be dead constants");
  504. }
  505. // Delete old instructions and global.
  506. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
  507. GV->removeDeadConstantUsers();
  508. GV->eraseFromParent();
  509. ++NumSRA;
  510. assert(NewGlobals.size() > 0);
  511. return NewGlobals.begin()->second;
  512. }
  513. /// Return true if all users of the specified value will trap if the value is
  514. /// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid
  515. /// reprocessing them.
  516. static bool AllUsesOfValueWillTrapIfNull(const Value *V,
  517. SmallPtrSetImpl<const PHINode*> &PHIs) {
  518. for (const User *U : V->users()) {
  519. if (const Instruction *I = dyn_cast<Instruction>(U)) {
  520. // If null pointer is considered valid, then all uses are non-trapping.
  521. // Non address-space 0 globals have already been pruned by the caller.
  522. if (NullPointerIsDefined(I->getFunction()))
  523. return false;
  524. }
  525. if (isa<LoadInst>(U)) {
  526. // Will trap.
  527. } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  528. if (SI->getOperand(0) == V) {
  529. //cerr << "NONTRAPPING USE: " << *U;
  530. return false; // Storing the value.
  531. }
  532. } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
  533. if (CI->getCalledOperand() != V) {
  534. //cerr << "NONTRAPPING USE: " << *U;
  535. return false; // Not calling the ptr
  536. }
  537. } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
  538. if (II->getCalledOperand() != V) {
  539. //cerr << "NONTRAPPING USE: " << *U;
  540. return false; // Not calling the ptr
  541. }
  542. } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
  543. if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
  544. } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
  545. if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
  546. } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
  547. // If we've already seen this phi node, ignore it, it has already been
  548. // checked.
  549. if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
  550. return false;
  551. } else if (isa<ICmpInst>(U) &&
  552. !ICmpInst::isSigned(cast<ICmpInst>(U)->getPredicate()) &&
  553. isa<LoadInst>(U->getOperand(0)) &&
  554. isa<ConstantPointerNull>(U->getOperand(1))) {
  555. assert(isa<GlobalValue>(cast<LoadInst>(U->getOperand(0))
  556. ->getPointerOperand()
  557. ->stripPointerCasts()) &&
  558. "Should be GlobalVariable");
  559. // This and only this kind of non-signed ICmpInst is to be replaced with
  560. // the comparing of the value of the created global init bool later in
  561. // optimizeGlobalAddressOfAllocation for the global variable.
  562. } else {
  563. //cerr << "NONTRAPPING USE: " << *U;
  564. return false;
  565. }
  566. }
  567. return true;
  568. }
  569. /// Return true if all uses of any loads from GV will trap if the loaded value
  570. /// is null. Note that this also permits comparisons of the loaded value
  571. /// against null, as a special case.
  572. static bool allUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
  573. SmallVector<const Value *, 4> Worklist;
  574. Worklist.push_back(GV);
  575. while (!Worklist.empty()) {
  576. const Value *P = Worklist.pop_back_val();
  577. for (auto *U : P->users()) {
  578. if (auto *LI = dyn_cast<LoadInst>(U)) {
  579. SmallPtrSet<const PHINode *, 8> PHIs;
  580. if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
  581. return false;
  582. } else if (auto *SI = dyn_cast<StoreInst>(U)) {
  583. // Ignore stores to the global.
  584. if (SI->getPointerOperand() != P)
  585. return false;
  586. } else if (auto *CE = dyn_cast<ConstantExpr>(U)) {
  587. if (CE->stripPointerCasts() != GV)
  588. return false;
  589. // Check further the ConstantExpr.
  590. Worklist.push_back(CE);
  591. } else {
  592. // We don't know or understand this user, bail out.
  593. return false;
  594. }
  595. }
  596. }
  597. return true;
  598. }
  599. /// Get all the loads/store uses for global variable \p GV.
  600. static void allUsesOfLoadAndStores(GlobalVariable *GV,
  601. SmallVector<Value *, 4> &Uses) {
  602. SmallVector<Value *, 4> Worklist;
  603. Worklist.push_back(GV);
  604. while (!Worklist.empty()) {
  605. auto *P = Worklist.pop_back_val();
  606. for (auto *U : P->users()) {
  607. if (auto *CE = dyn_cast<ConstantExpr>(U)) {
  608. Worklist.push_back(CE);
  609. continue;
  610. }
  611. assert((isa<LoadInst>(U) || isa<StoreInst>(U)) &&
  612. "Expect only load or store instructions");
  613. Uses.push_back(U);
  614. }
  615. }
  616. }
  617. static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
  618. bool Changed = false;
  619. for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
  620. Instruction *I = cast<Instruction>(*UI++);
  621. // Uses are non-trapping if null pointer is considered valid.
  622. // Non address-space 0 globals are already pruned by the caller.
  623. if (NullPointerIsDefined(I->getFunction()))
  624. return false;
  625. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  626. LI->setOperand(0, NewV);
  627. Changed = true;
  628. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  629. if (SI->getOperand(1) == V) {
  630. SI->setOperand(1, NewV);
  631. Changed = true;
  632. }
  633. } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
  634. CallBase *CB = cast<CallBase>(I);
  635. if (CB->getCalledOperand() == V) {
  636. // Calling through the pointer! Turn into a direct call, but be careful
  637. // that the pointer is not also being passed as an argument.
  638. CB->setCalledOperand(NewV);
  639. Changed = true;
  640. bool PassedAsArg = false;
  641. for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
  642. if (CB->getArgOperand(i) == V) {
  643. PassedAsArg = true;
  644. CB->setArgOperand(i, NewV);
  645. }
  646. if (PassedAsArg) {
  647. // Being passed as an argument also. Be careful to not invalidate UI!
  648. UI = V->user_begin();
  649. }
  650. }
  651. } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
  652. Changed |= OptimizeAwayTrappingUsesOfValue(CI,
  653. ConstantExpr::getCast(CI->getOpcode(),
  654. NewV, CI->getType()));
  655. if (CI->use_empty()) {
  656. Changed = true;
  657. CI->eraseFromParent();
  658. }
  659. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  660. // Should handle GEP here.
  661. SmallVector<Constant*, 8> Idxs;
  662. Idxs.reserve(GEPI->getNumOperands()-1);
  663. for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
  664. i != e; ++i)
  665. if (Constant *C = dyn_cast<Constant>(*i))
  666. Idxs.push_back(C);
  667. else
  668. break;
  669. if (Idxs.size() == GEPI->getNumOperands()-1)
  670. Changed |= OptimizeAwayTrappingUsesOfValue(
  671. GEPI, ConstantExpr::getGetElementPtr(GEPI->getSourceElementType(),
  672. NewV, Idxs));
  673. if (GEPI->use_empty()) {
  674. Changed = true;
  675. GEPI->eraseFromParent();
  676. }
  677. }
  678. }
  679. return Changed;
  680. }
  681. /// The specified global has only one non-null value stored into it. If there
  682. /// are uses of the loaded value that would trap if the loaded value is
  683. /// dynamically null, then we know that they cannot be reachable with a null
  684. /// optimize away the load.
  685. static bool OptimizeAwayTrappingUsesOfLoads(
  686. GlobalVariable *GV, Constant *LV, const DataLayout &DL,
  687. function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  688. bool Changed = false;
  689. // Keep track of whether we are able to remove all the uses of the global
  690. // other than the store that defines it.
  691. bool AllNonStoreUsesGone = true;
  692. // Replace all uses of loads with uses of uses of the stored value.
  693. for (User *GlobalUser : llvm::make_early_inc_range(GV->users())) {
  694. if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
  695. Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
  696. // If we were able to delete all uses of the loads
  697. if (LI->use_empty()) {
  698. LI->eraseFromParent();
  699. Changed = true;
  700. } else {
  701. AllNonStoreUsesGone = false;
  702. }
  703. } else if (isa<StoreInst>(GlobalUser)) {
  704. // Ignore the store that stores "LV" to the global.
  705. assert(GlobalUser->getOperand(1) == GV &&
  706. "Must be storing *to* the global");
  707. } else {
  708. AllNonStoreUsesGone = false;
  709. // If we get here we could have other crazy uses that are transitively
  710. // loaded.
  711. assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
  712. isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
  713. isa<BitCastInst>(GlobalUser) ||
  714. isa<GetElementPtrInst>(GlobalUser)) &&
  715. "Only expect load and stores!");
  716. }
  717. }
  718. if (Changed) {
  719. LLVM_DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV
  720. << "\n");
  721. ++NumGlobUses;
  722. }
  723. // If we nuked all of the loads, then none of the stores are needed either,
  724. // nor is the global.
  725. if (AllNonStoreUsesGone) {
  726. if (isLeakCheckerRoot(GV)) {
  727. Changed |= CleanupPointerRootUsers(GV, GetTLI);
  728. } else {
  729. Changed = true;
  730. CleanupConstantGlobalUsers(GV, DL);
  731. }
  732. if (GV->use_empty()) {
  733. LLVM_DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
  734. Changed = true;
  735. GV->eraseFromParent();
  736. ++NumDeleted;
  737. }
  738. }
  739. return Changed;
  740. }
  741. /// Walk the use list of V, constant folding all of the instructions that are
  742. /// foldable.
  743. static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
  744. TargetLibraryInfo *TLI) {
  745. for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
  746. if (Instruction *I = dyn_cast<Instruction>(*UI++))
  747. if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
  748. I->replaceAllUsesWith(NewC);
  749. // Advance UI to the next non-I use to avoid invalidating it!
  750. // Instructions could multiply use V.
  751. while (UI != E && *UI == I)
  752. ++UI;
  753. if (isInstructionTriviallyDead(I, TLI))
  754. I->eraseFromParent();
  755. }
  756. }
  757. /// This function takes the specified global variable, and transforms the
  758. /// program as if it always contained the result of the specified malloc.
  759. /// Because it is always the result of the specified malloc, there is no reason
  760. /// to actually DO the malloc. Instead, turn the malloc into a global, and any
  761. /// loads of GV as uses of the new global.
  762. static GlobalVariable *
  763. OptimizeGlobalAddressOfAllocation(GlobalVariable *GV, CallInst *CI,
  764. uint64_t AllocSize, Constant *InitVal,
  765. const DataLayout &DL,
  766. TargetLibraryInfo *TLI) {
  767. LLVM_DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI
  768. << '\n');
  769. // Create global of type [AllocSize x i8].
  770. Type *GlobalType = ArrayType::get(Type::getInt8Ty(GV->getContext()),
  771. AllocSize);
  772. // Create the new global variable. The contents of the allocated memory is
  773. // undefined initially, so initialize with an undef value.
  774. GlobalVariable *NewGV = new GlobalVariable(
  775. *GV->getParent(), GlobalType, false, GlobalValue::InternalLinkage,
  776. UndefValue::get(GlobalType), GV->getName() + ".body", nullptr,
  777. GV->getThreadLocalMode());
  778. // Initialize the global at the point of the original call. Note that this
  779. // is a different point from the initialization referred to below for the
  780. // nullability handling. Sublety: We have not proven the original global was
  781. // only initialized once. As such, we can not fold this into the initializer
  782. // of the new global as may need to re-init the storage multiple times.
  783. if (!isa<UndefValue>(InitVal)) {
  784. IRBuilder<> Builder(CI->getNextNode());
  785. // TODO: Use alignment above if align!=1
  786. Builder.CreateMemSet(NewGV, InitVal, AllocSize, None);
  787. }
  788. // Update users of the allocation to use the new global instead.
  789. BitCastInst *TheBC = nullptr;
  790. while (!CI->use_empty()) {
  791. Instruction *User = cast<Instruction>(CI->user_back());
  792. if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
  793. if (BCI->getType() == NewGV->getType()) {
  794. BCI->replaceAllUsesWith(NewGV);
  795. BCI->eraseFromParent();
  796. } else {
  797. BCI->setOperand(0, NewGV);
  798. }
  799. } else {
  800. if (!TheBC)
  801. TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
  802. User->replaceUsesOfWith(CI, TheBC);
  803. }
  804. }
  805. SmallPtrSet<Constant *, 1> RepValues;
  806. RepValues.insert(NewGV);
  807. // If there is a comparison against null, we will insert a global bool to
  808. // keep track of whether the global was initialized yet or not.
  809. GlobalVariable *InitBool =
  810. new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
  811. GlobalValue::InternalLinkage,
  812. ConstantInt::getFalse(GV->getContext()),
  813. GV->getName()+".init", GV->getThreadLocalMode());
  814. bool InitBoolUsed = false;
  815. // Loop over all instruction uses of GV, processing them in turn.
  816. SmallVector<Value *, 4> Guses;
  817. allUsesOfLoadAndStores(GV, Guses);
  818. for (auto *U : Guses) {
  819. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  820. // The global is initialized when the store to it occurs. If the stored
  821. // value is null value, the global bool is set to false, otherwise true.
  822. new StoreInst(ConstantInt::getBool(
  823. GV->getContext(),
  824. !isa<ConstantPointerNull>(SI->getValueOperand())),
  825. InitBool, false, Align(1), SI->getOrdering(),
  826. SI->getSyncScopeID(), SI);
  827. SI->eraseFromParent();
  828. continue;
  829. }
  830. LoadInst *LI = cast<LoadInst>(U);
  831. while (!LI->use_empty()) {
  832. Use &LoadUse = *LI->use_begin();
  833. ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
  834. if (!ICI) {
  835. auto *CE = ConstantExpr::getBitCast(NewGV, LI->getType());
  836. RepValues.insert(CE);
  837. LoadUse.set(CE);
  838. continue;
  839. }
  840. // Replace the cmp X, 0 with a use of the bool value.
  841. Value *LV = new LoadInst(InitBool->getValueType(), InitBool,
  842. InitBool->getName() + ".val", false, Align(1),
  843. LI->getOrdering(), LI->getSyncScopeID(), LI);
  844. InitBoolUsed = true;
  845. switch (ICI->getPredicate()) {
  846. default: llvm_unreachable("Unknown ICmp Predicate!");
  847. case ICmpInst::ICMP_ULT: // X < null -> always false
  848. LV = ConstantInt::getFalse(GV->getContext());
  849. break;
  850. case ICmpInst::ICMP_UGE: // X >= null -> always true
  851. LV = ConstantInt::getTrue(GV->getContext());
  852. break;
  853. case ICmpInst::ICMP_ULE:
  854. case ICmpInst::ICMP_EQ:
  855. LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
  856. break;
  857. case ICmpInst::ICMP_NE:
  858. case ICmpInst::ICMP_UGT:
  859. break; // no change.
  860. }
  861. ICI->replaceAllUsesWith(LV);
  862. ICI->eraseFromParent();
  863. }
  864. LI->eraseFromParent();
  865. }
  866. // If the initialization boolean was used, insert it, otherwise delete it.
  867. if (!InitBoolUsed) {
  868. while (!InitBool->use_empty()) // Delete initializations
  869. cast<StoreInst>(InitBool->user_back())->eraseFromParent();
  870. delete InitBool;
  871. } else
  872. GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
  873. // Now the GV is dead, nuke it and the allocation..
  874. GV->eraseFromParent();
  875. CI->eraseFromParent();
  876. // To further other optimizations, loop over all users of NewGV and try to
  877. // constant prop them. This will promote GEP instructions with constant
  878. // indices into GEP constant-exprs, which will allow global-opt to hack on it.
  879. for (auto *CE : RepValues)
  880. ConstantPropUsersOf(CE, DL, TLI);
  881. return NewGV;
  882. }
  883. /// Scan the use-list of GV checking to make sure that there are no complex uses
  884. /// of GV. We permit simple things like dereferencing the pointer, but not
  885. /// storing through the address, unless it is to the specified global.
  886. static bool
  887. valueIsOnlyUsedLocallyOrStoredToOneGlobal(const CallInst *CI,
  888. const GlobalVariable *GV) {
  889. SmallPtrSet<const Value *, 4> Visited;
  890. SmallVector<const Value *, 4> Worklist;
  891. Worklist.push_back(CI);
  892. while (!Worklist.empty()) {
  893. const Value *V = Worklist.pop_back_val();
  894. if (!Visited.insert(V).second)
  895. continue;
  896. for (const Use &VUse : V->uses()) {
  897. const User *U = VUse.getUser();
  898. if (isa<LoadInst>(U) || isa<CmpInst>(U))
  899. continue; // Fine, ignore.
  900. if (auto *SI = dyn_cast<StoreInst>(U)) {
  901. if (SI->getValueOperand() == V &&
  902. SI->getPointerOperand()->stripPointerCasts() != GV)
  903. return false; // Storing the pointer not into GV... bad.
  904. continue; // Otherwise, storing through it, or storing into GV... fine.
  905. }
  906. if (auto *BCI = dyn_cast<BitCastInst>(U)) {
  907. Worklist.push_back(BCI);
  908. continue;
  909. }
  910. if (auto *GEPI = dyn_cast<GetElementPtrInst>(U)) {
  911. Worklist.push_back(GEPI);
  912. continue;
  913. }
  914. return false;
  915. }
  916. }
  917. return true;
  918. }
  919. /// If we have a global that is only initialized with a fixed size allocation
  920. /// try to transform the program to use global memory instead of heap
  921. /// allocated memory. This eliminates dynamic allocation, avoids an indirection
  922. /// accessing the data, and exposes the resultant global to further GlobalOpt.
  923. static bool tryToOptimizeStoreOfAllocationToGlobal(GlobalVariable *GV,
  924. CallInst *CI,
  925. AtomicOrdering Ordering,
  926. const DataLayout &DL,
  927. TargetLibraryInfo *TLI) {
  928. if (!isAllocRemovable(CI, TLI))
  929. // Must be able to remove the call when we get done..
  930. return false;
  931. Type *Int8Ty = Type::getInt8Ty(CI->getFunction()->getContext());
  932. Constant *InitVal = getInitialValueOfAllocation(CI, TLI, Int8Ty);
  933. if (!InitVal)
  934. // Must be able to emit a memset for initialization
  935. return false;
  936. uint64_t AllocSize;
  937. if (!getObjectSize(CI, AllocSize, DL, TLI, ObjectSizeOpts()))
  938. return false;
  939. // Restrict this transformation to only working on small allocations
  940. // (2048 bytes currently), as we don't want to introduce a 16M global or
  941. // something.
  942. if (AllocSize >= 2048)
  943. return false;
  944. // We can't optimize this global unless all uses of it are *known* to be
  945. // of the malloc value, not of the null initializer value (consider a use
  946. // that compares the global's value against zero to see if the malloc has
  947. // been reached). To do this, we check to see if all uses of the global
  948. // would trap if the global were null: this proves that they must all
  949. // happen after the malloc.
  950. if (!allUsesOfLoadedValueWillTrapIfNull(GV))
  951. return false;
  952. // We can't optimize this if the malloc itself is used in a complex way,
  953. // for example, being stored into multiple globals. This allows the
  954. // malloc to be stored into the specified global, loaded, gep, icmp'd.
  955. // These are all things we could transform to using the global for.
  956. if (!valueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV))
  957. return false;
  958. OptimizeGlobalAddressOfAllocation(GV, CI, AllocSize, InitVal, DL, TLI);
  959. return true;
  960. }
  961. // Try to optimize globals based on the knowledge that only one value (besides
  962. // its initializer) is ever stored to the global.
  963. static bool
  964. optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
  965. AtomicOrdering Ordering, const DataLayout &DL,
  966. function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  967. // Ignore no-op GEPs and bitcasts.
  968. StoredOnceVal = StoredOnceVal->stripPointerCasts();
  969. // If we are dealing with a pointer global that is initialized to null and
  970. // only has one (non-null) value stored into it, then we can optimize any
  971. // users of the loaded value (often calls and loads) that would trap if the
  972. // value was null.
  973. if (GV->getInitializer()->getType()->isPointerTy() &&
  974. GV->getInitializer()->isNullValue() &&
  975. StoredOnceVal->getType()->isPointerTy() &&
  976. !NullPointerIsDefined(
  977. nullptr /* F */,
  978. GV->getInitializer()->getType()->getPointerAddressSpace())) {
  979. if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
  980. if (GV->getInitializer()->getType() != SOVC->getType())
  981. SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
  982. // Optimize away any trapping uses of the loaded value.
  983. if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, GetTLI))
  984. return true;
  985. } else if (isAllocationFn(StoredOnceVal, GetTLI)) {
  986. if (auto *CI = dyn_cast<CallInst>(StoredOnceVal)) {
  987. auto *TLI = &GetTLI(*CI->getFunction());
  988. if (tryToOptimizeStoreOfAllocationToGlobal(GV, CI, Ordering, DL, TLI))
  989. return true;
  990. }
  991. }
  992. }
  993. return false;
  994. }
  995. /// At this point, we have learned that the only two values ever stored into GV
  996. /// are its initializer and OtherVal. See if we can shrink the global into a
  997. /// boolean and select between the two values whenever it is used. This exposes
  998. /// the values to other scalar optimizations.
  999. static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
  1000. Type *GVElType = GV->getValueType();
  1001. // If GVElType is already i1, it is already shrunk. If the type of the GV is
  1002. // an FP value, pointer or vector, don't do this optimization because a select
  1003. // between them is very expensive and unlikely to lead to later
  1004. // simplification. In these cases, we typically end up with "cond ? v1 : v2"
  1005. // where v1 and v2 both require constant pool loads, a big loss.
  1006. if (GVElType == Type::getInt1Ty(GV->getContext()) ||
  1007. GVElType->isFloatingPointTy() ||
  1008. GVElType->isPointerTy() || GVElType->isVectorTy())
  1009. return false;
  1010. // Walk the use list of the global seeing if all the uses are load or store.
  1011. // If there is anything else, bail out.
  1012. for (User *U : GV->users()) {
  1013. if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
  1014. return false;
  1015. if (getLoadStoreType(U) != GVElType)
  1016. return false;
  1017. }
  1018. LLVM_DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n");
  1019. // Create the new global, initializing it to false.
  1020. GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
  1021. false,
  1022. GlobalValue::InternalLinkage,
  1023. ConstantInt::getFalse(GV->getContext()),
  1024. GV->getName()+".b",
  1025. GV->getThreadLocalMode(),
  1026. GV->getType()->getAddressSpace());
  1027. NewGV->copyAttributesFrom(GV);
  1028. GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
  1029. Constant *InitVal = GV->getInitializer();
  1030. assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
  1031. "No reason to shrink to bool!");
  1032. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  1033. GV->getDebugInfo(GVs);
  1034. // If initialized to zero and storing one into the global, we can use a cast
  1035. // instead of a select to synthesize the desired value.
  1036. bool IsOneZero = false;
  1037. bool EmitOneOrZero = true;
  1038. auto *CI = dyn_cast<ConstantInt>(OtherVal);
  1039. if (CI && CI->getValue().getActiveBits() <= 64) {
  1040. IsOneZero = InitVal->isNullValue() && CI->isOne();
  1041. auto *CIInit = dyn_cast<ConstantInt>(GV->getInitializer());
  1042. if (CIInit && CIInit->getValue().getActiveBits() <= 64) {
  1043. uint64_t ValInit = CIInit->getZExtValue();
  1044. uint64_t ValOther = CI->getZExtValue();
  1045. uint64_t ValMinus = ValOther - ValInit;
  1046. for(auto *GVe : GVs){
  1047. DIGlobalVariable *DGV = GVe->getVariable();
  1048. DIExpression *E = GVe->getExpression();
  1049. const DataLayout &DL = GV->getParent()->getDataLayout();
  1050. unsigned SizeInOctets =
  1051. DL.getTypeAllocSizeInBits(NewGV->getValueType()) / 8;
  1052. // It is expected that the address of global optimized variable is on
  1053. // top of the stack. After optimization, value of that variable will
  1054. // be ether 0 for initial value or 1 for other value. The following
  1055. // expression should return constant integer value depending on the
  1056. // value at global object address:
  1057. // val * (ValOther - ValInit) + ValInit:
  1058. // DW_OP_deref DW_OP_constu <ValMinus>
  1059. // DW_OP_mul DW_OP_constu <ValInit> DW_OP_plus DW_OP_stack_value
  1060. SmallVector<uint64_t, 12> Ops = {
  1061. dwarf::DW_OP_deref_size, SizeInOctets,
  1062. dwarf::DW_OP_constu, ValMinus,
  1063. dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit,
  1064. dwarf::DW_OP_plus};
  1065. bool WithStackValue = true;
  1066. E = DIExpression::prependOpcodes(E, Ops, WithStackValue);
  1067. DIGlobalVariableExpression *DGVE =
  1068. DIGlobalVariableExpression::get(NewGV->getContext(), DGV, E);
  1069. NewGV->addDebugInfo(DGVE);
  1070. }
  1071. EmitOneOrZero = false;
  1072. }
  1073. }
  1074. if (EmitOneOrZero) {
  1075. // FIXME: This will only emit address for debugger on which will
  1076. // be written only 0 or 1.
  1077. for(auto *GV : GVs)
  1078. NewGV->addDebugInfo(GV);
  1079. }
  1080. while (!GV->use_empty()) {
  1081. Instruction *UI = cast<Instruction>(GV->user_back());
  1082. if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  1083. // Change the store into a boolean store.
  1084. bool StoringOther = SI->getOperand(0) == OtherVal;
  1085. // Only do this if we weren't storing a loaded value.
  1086. Value *StoreVal;
  1087. if (StoringOther || SI->getOperand(0) == InitVal) {
  1088. StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
  1089. StoringOther);
  1090. } else {
  1091. // Otherwise, we are storing a previously loaded copy. To do this,
  1092. // change the copy from copying the original value to just copying the
  1093. // bool.
  1094. Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
  1095. // If we've already replaced the input, StoredVal will be a cast or
  1096. // select instruction. If not, it will be a load of the original
  1097. // global.
  1098. if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
  1099. assert(LI->getOperand(0) == GV && "Not a copy!");
  1100. // Insert a new load, to preserve the saved value.
  1101. StoreVal = new LoadInst(NewGV->getValueType(), NewGV,
  1102. LI->getName() + ".b", false, Align(1),
  1103. LI->getOrdering(), LI->getSyncScopeID(), LI);
  1104. } else {
  1105. assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
  1106. "This is not a form that we understand!");
  1107. StoreVal = StoredVal->getOperand(0);
  1108. assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
  1109. }
  1110. }
  1111. StoreInst *NSI =
  1112. new StoreInst(StoreVal, NewGV, false, Align(1), SI->getOrdering(),
  1113. SI->getSyncScopeID(), SI);
  1114. NSI->setDebugLoc(SI->getDebugLoc());
  1115. } else {
  1116. // Change the load into a load of bool then a select.
  1117. LoadInst *LI = cast<LoadInst>(UI);
  1118. LoadInst *NLI = new LoadInst(NewGV->getValueType(), NewGV,
  1119. LI->getName() + ".b", false, Align(1),
  1120. LI->getOrdering(), LI->getSyncScopeID(), LI);
  1121. Instruction *NSI;
  1122. if (IsOneZero)
  1123. NSI = new ZExtInst(NLI, LI->getType(), "", LI);
  1124. else
  1125. NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
  1126. NSI->takeName(LI);
  1127. // Since LI is split into two instructions, NLI and NSI both inherit the
  1128. // same DebugLoc
  1129. NLI->setDebugLoc(LI->getDebugLoc());
  1130. NSI->setDebugLoc(LI->getDebugLoc());
  1131. LI->replaceAllUsesWith(NSI);
  1132. }
  1133. UI->eraseFromParent();
  1134. }
  1135. // Retain the name of the old global variable. People who are debugging their
  1136. // programs may expect these variables to be named the same.
  1137. NewGV->takeName(GV);
  1138. GV->eraseFromParent();
  1139. return true;
  1140. }
  1141. static bool deleteIfDead(
  1142. GlobalValue &GV, SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
  1143. GV.removeDeadConstantUsers();
  1144. if (!GV.isDiscardableIfUnused() && !GV.isDeclaration())
  1145. return false;
  1146. if (const Comdat *C = GV.getComdat())
  1147. if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C))
  1148. return false;
  1149. bool Dead;
  1150. if (auto *F = dyn_cast<Function>(&GV))
  1151. Dead = (F->isDeclaration() && F->use_empty()) || F->isDefTriviallyDead();
  1152. else
  1153. Dead = GV.use_empty();
  1154. if (!Dead)
  1155. return false;
  1156. LLVM_DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n");
  1157. GV.eraseFromParent();
  1158. ++NumDeleted;
  1159. return true;
  1160. }
  1161. static bool isPointerValueDeadOnEntryToFunction(
  1162. const Function *F, GlobalValue *GV,
  1163. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  1164. // Find all uses of GV. We expect them all to be in F, and if we can't
  1165. // identify any of the uses we bail out.
  1166. //
  1167. // On each of these uses, identify if the memory that GV points to is
  1168. // used/required/live at the start of the function. If it is not, for example
  1169. // if the first thing the function does is store to the GV, the GV can
  1170. // possibly be demoted.
  1171. //
  1172. // We don't do an exhaustive search for memory operations - simply look
  1173. // through bitcasts as they're quite common and benign.
  1174. const DataLayout &DL = GV->getParent()->getDataLayout();
  1175. SmallVector<LoadInst *, 4> Loads;
  1176. SmallVector<StoreInst *, 4> Stores;
  1177. for (auto *U : GV->users()) {
  1178. if (Operator::getOpcode(U) == Instruction::BitCast) {
  1179. for (auto *UU : U->users()) {
  1180. if (auto *LI = dyn_cast<LoadInst>(UU))
  1181. Loads.push_back(LI);
  1182. else if (auto *SI = dyn_cast<StoreInst>(UU))
  1183. Stores.push_back(SI);
  1184. else
  1185. return false;
  1186. }
  1187. continue;
  1188. }
  1189. Instruction *I = dyn_cast<Instruction>(U);
  1190. if (!I)
  1191. return false;
  1192. assert(I->getParent()->getParent() == F);
  1193. if (auto *LI = dyn_cast<LoadInst>(I))
  1194. Loads.push_back(LI);
  1195. else if (auto *SI = dyn_cast<StoreInst>(I))
  1196. Stores.push_back(SI);
  1197. else
  1198. return false;
  1199. }
  1200. // We have identified all uses of GV into loads and stores. Now check if all
  1201. // of them are known not to depend on the value of the global at the function
  1202. // entry point. We do this by ensuring that every load is dominated by at
  1203. // least one store.
  1204. auto &DT = LookupDomTree(*const_cast<Function *>(F));
  1205. // The below check is quadratic. Check we're not going to do too many tests.
  1206. // FIXME: Even though this will always have worst-case quadratic time, we
  1207. // could put effort into minimizing the average time by putting stores that
  1208. // have been shown to dominate at least one load at the beginning of the
  1209. // Stores array, making subsequent dominance checks more likely to succeed
  1210. // early.
  1211. //
  1212. // The threshold here is fairly large because global->local demotion is a
  1213. // very powerful optimization should it fire.
  1214. const unsigned Threshold = 100;
  1215. if (Loads.size() * Stores.size() > Threshold)
  1216. return false;
  1217. for (auto *L : Loads) {
  1218. auto *LTy = L->getType();
  1219. if (none_of(Stores, [&](const StoreInst *S) {
  1220. auto *STy = S->getValueOperand()->getType();
  1221. // The load is only dominated by the store if DomTree says so
  1222. // and the number of bits loaded in L is less than or equal to
  1223. // the number of bits stored in S.
  1224. return DT.dominates(S, L) &&
  1225. DL.getTypeStoreSize(LTy).getFixedSize() <=
  1226. DL.getTypeStoreSize(STy).getFixedSize();
  1227. }))
  1228. return false;
  1229. }
  1230. // All loads have known dependences inside F, so the global can be localized.
  1231. return true;
  1232. }
  1233. /// C may have non-instruction users. Can all of those users be turned into
  1234. /// instructions?
  1235. static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C) {
  1236. // We don't do this exhaustively. The most common pattern that we really need
  1237. // to care about is a constant GEP or constant bitcast - so just looking
  1238. // through one single ConstantExpr.
  1239. //
  1240. // The set of constants that this function returns true for must be able to be
  1241. // handled by makeAllConstantUsesInstructions.
  1242. for (auto *U : C->users()) {
  1243. if (isa<Instruction>(U))
  1244. continue;
  1245. if (!isa<ConstantExpr>(U))
  1246. // Non instruction, non-constantexpr user; cannot convert this.
  1247. return false;
  1248. for (auto *UU : U->users())
  1249. if (!isa<Instruction>(UU))
  1250. // A constantexpr used by another constant. We don't try and recurse any
  1251. // further but just bail out at this point.
  1252. return false;
  1253. }
  1254. return true;
  1255. }
  1256. /// C may have non-instruction users, and
  1257. /// allNonInstructionUsersCanBeMadeInstructions has returned true. Convert the
  1258. /// non-instruction users to instructions.
  1259. static void makeAllConstantUsesInstructions(Constant *C) {
  1260. SmallVector<ConstantExpr*,4> Users;
  1261. for (auto *U : C->users()) {
  1262. if (isa<ConstantExpr>(U))
  1263. Users.push_back(cast<ConstantExpr>(U));
  1264. else
  1265. // We should never get here; allNonInstructionUsersCanBeMadeInstructions
  1266. // should not have returned true for C.
  1267. assert(
  1268. isa<Instruction>(U) &&
  1269. "Can't transform non-constantexpr non-instruction to instruction!");
  1270. }
  1271. SmallVector<Value*,4> UUsers;
  1272. for (auto *U : Users) {
  1273. UUsers.clear();
  1274. append_range(UUsers, U->users());
  1275. for (auto *UU : UUsers) {
  1276. Instruction *UI = cast<Instruction>(UU);
  1277. Instruction *NewU = U->getAsInstruction(UI);
  1278. UI->replaceUsesOfWith(U, NewU);
  1279. }
  1280. // We've replaced all the uses, so destroy the constant. (destroyConstant
  1281. // will update value handles and metadata.)
  1282. U->destroyConstant();
  1283. }
  1284. }
  1285. /// Analyze the specified global variable and optimize
  1286. /// it if possible. If we make a change, return true.
  1287. static bool
  1288. processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS,
  1289. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1290. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1291. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  1292. auto &DL = GV->getParent()->getDataLayout();
  1293. // If this is a first class global and has only one accessing function and
  1294. // this function is non-recursive, we replace the global with a local alloca
  1295. // in this function.
  1296. //
  1297. // NOTE: It doesn't make sense to promote non-single-value types since we
  1298. // are just replacing static memory to stack memory.
  1299. //
  1300. // If the global is in different address space, don't bring it to stack.
  1301. if (!GS.HasMultipleAccessingFunctions &&
  1302. GS.AccessingFunction &&
  1303. GV->getValueType()->isSingleValueType() &&
  1304. GV->getType()->getAddressSpace() == 0 &&
  1305. !GV->isExternallyInitialized() &&
  1306. allNonInstructionUsersCanBeMadeInstructions(GV) &&
  1307. GS.AccessingFunction->doesNotRecurse() &&
  1308. isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV,
  1309. LookupDomTree)) {
  1310. const DataLayout &DL = GV->getParent()->getDataLayout();
  1311. LLVM_DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n");
  1312. Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
  1313. ->getEntryBlock().begin());
  1314. Type *ElemTy = GV->getValueType();
  1315. // FIXME: Pass Global's alignment when globals have alignment
  1316. AllocaInst *Alloca = new AllocaInst(ElemTy, DL.getAllocaAddrSpace(), nullptr,
  1317. GV->getName(), &FirstI);
  1318. if (!isa<UndefValue>(GV->getInitializer()))
  1319. new StoreInst(GV->getInitializer(), Alloca, &FirstI);
  1320. makeAllConstantUsesInstructions(GV);
  1321. GV->replaceAllUsesWith(Alloca);
  1322. GV->eraseFromParent();
  1323. ++NumLocalized;
  1324. return true;
  1325. }
  1326. bool Changed = false;
  1327. // If the global is never loaded (but may be stored to), it is dead.
  1328. // Delete it now.
  1329. if (!GS.IsLoaded) {
  1330. LLVM_DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n");
  1331. if (isLeakCheckerRoot(GV)) {
  1332. // Delete any constant stores to the global.
  1333. Changed = CleanupPointerRootUsers(GV, GetTLI);
  1334. } else {
  1335. // Delete any stores we can find to the global. We may not be able to
  1336. // make it completely dead though.
  1337. Changed = CleanupConstantGlobalUsers(GV, DL);
  1338. }
  1339. // If the global is dead now, delete it.
  1340. if (GV->use_empty()) {
  1341. GV->eraseFromParent();
  1342. ++NumDeleted;
  1343. Changed = true;
  1344. }
  1345. return Changed;
  1346. }
  1347. if (GS.StoredType <= GlobalStatus::InitializerStored) {
  1348. LLVM_DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
  1349. // Don't actually mark a global constant if it's atomic because atomic loads
  1350. // are implemented by a trivial cmpxchg in some edge-cases and that usually
  1351. // requires write access to the variable even if it's not actually changed.
  1352. if (GS.Ordering == AtomicOrdering::NotAtomic) {
  1353. assert(!GV->isConstant() && "Expected a non-constant global");
  1354. GV->setConstant(true);
  1355. Changed = true;
  1356. }
  1357. // Clean up any obviously simplifiable users now.
  1358. Changed |= CleanupConstantGlobalUsers(GV, DL);
  1359. // If the global is dead now, just nuke it.
  1360. if (GV->use_empty()) {
  1361. LLVM_DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
  1362. << "all users and delete global!\n");
  1363. GV->eraseFromParent();
  1364. ++NumDeleted;
  1365. return true;
  1366. }
  1367. // Fall through to the next check; see if we can optimize further.
  1368. ++NumMarked;
  1369. }
  1370. if (!GV->getInitializer()->getType()->isSingleValueType()) {
  1371. const DataLayout &DL = GV->getParent()->getDataLayout();
  1372. if (SRAGlobal(GV, DL))
  1373. return true;
  1374. }
  1375. Value *StoredOnceValue = GS.getStoredOnceValue();
  1376. if (GS.StoredType == GlobalStatus::StoredOnce && StoredOnceValue) {
  1377. // Avoid speculating constant expressions that might trap (div/rem).
  1378. auto *SOVConstant = dyn_cast<Constant>(StoredOnceValue);
  1379. if (SOVConstant && SOVConstant->canTrap())
  1380. return Changed;
  1381. Function &StoreFn =
  1382. const_cast<Function &>(*GS.StoredOnceStore->getFunction());
  1383. bool CanHaveNonUndefGlobalInitializer =
  1384. GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace(
  1385. GV->getType()->getAddressSpace());
  1386. // If the initial value for the global was an undef value, and if only
  1387. // one other value was stored into it, we can just change the
  1388. // initializer to be the stored value, then delete all stores to the
  1389. // global. This allows us to mark it constant.
  1390. // This is restricted to address spaces that allow globals to have
  1391. // initializers. NVPTX, for example, does not support initializers for
  1392. // shared memory (AS 3).
  1393. if (SOVConstant && isa<UndefValue>(GV->getInitializer()) &&
  1394. DL.getTypeAllocSize(SOVConstant->getType()) ==
  1395. DL.getTypeAllocSize(GV->getValueType()) &&
  1396. CanHaveNonUndefGlobalInitializer) {
  1397. if (SOVConstant->getType() == GV->getValueType()) {
  1398. // Change the initializer in place.
  1399. GV->setInitializer(SOVConstant);
  1400. } else {
  1401. // Create a new global with adjusted type.
  1402. auto *NGV = new GlobalVariable(
  1403. *GV->getParent(), SOVConstant->getType(), GV->isConstant(),
  1404. GV->getLinkage(), SOVConstant, "", GV, GV->getThreadLocalMode(),
  1405. GV->getAddressSpace());
  1406. NGV->takeName(GV);
  1407. NGV->copyAttributesFrom(GV);
  1408. GV->replaceAllUsesWith(ConstantExpr::getBitCast(NGV, GV->getType()));
  1409. GV->eraseFromParent();
  1410. GV = NGV;
  1411. }
  1412. // Clean up any obviously simplifiable users now.
  1413. CleanupConstantGlobalUsers(GV, DL);
  1414. if (GV->use_empty()) {
  1415. LLVM_DEBUG(dbgs() << " *** Substituting initializer allowed us to "
  1416. << "simplify all users and delete global!\n");
  1417. GV->eraseFromParent();
  1418. ++NumDeleted;
  1419. }
  1420. ++NumSubstitute;
  1421. return true;
  1422. }
  1423. // Try to optimize globals based on the knowledge that only one value
  1424. // (besides its initializer) is ever stored to the global.
  1425. if (optimizeOnceStoredGlobal(GV, StoredOnceValue, GS.Ordering, DL, GetTLI))
  1426. return true;
  1427. // Otherwise, if the global was not a boolean, we can shrink it to be a
  1428. // boolean. Skip this optimization for AS that doesn't allow an initializer.
  1429. if (SOVConstant && GS.Ordering == AtomicOrdering::NotAtomic &&
  1430. (!isa<UndefValue>(GV->getInitializer()) ||
  1431. CanHaveNonUndefGlobalInitializer)) {
  1432. if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
  1433. ++NumShrunkToBool;
  1434. return true;
  1435. }
  1436. }
  1437. }
  1438. return Changed;
  1439. }
  1440. /// Analyze the specified global variable and optimize it if possible. If we
  1441. /// make a change, return true.
  1442. static bool
  1443. processGlobal(GlobalValue &GV,
  1444. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1445. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1446. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  1447. if (GV.getName().startswith("llvm."))
  1448. return false;
  1449. GlobalStatus GS;
  1450. if (GlobalStatus::analyzeGlobal(&GV, GS))
  1451. return false;
  1452. bool Changed = false;
  1453. if (!GS.IsCompared && !GV.hasGlobalUnnamedAddr()) {
  1454. auto NewUnnamedAddr = GV.hasLocalLinkage() ? GlobalValue::UnnamedAddr::Global
  1455. : GlobalValue::UnnamedAddr::Local;
  1456. if (NewUnnamedAddr != GV.getUnnamedAddr()) {
  1457. GV.setUnnamedAddr(NewUnnamedAddr);
  1458. NumUnnamed++;
  1459. Changed = true;
  1460. }
  1461. }
  1462. // Do more involved optimizations if the global is internal.
  1463. if (!GV.hasLocalLinkage())
  1464. return Changed;
  1465. auto *GVar = dyn_cast<GlobalVariable>(&GV);
  1466. if (!GVar)
  1467. return Changed;
  1468. if (GVar->isConstant() || !GVar->hasInitializer())
  1469. return Changed;
  1470. return processInternalGlobal(GVar, GS, GetTTI, GetTLI, LookupDomTree) ||
  1471. Changed;
  1472. }
  1473. /// Walk all of the direct calls of the specified function, changing them to
  1474. /// FastCC.
  1475. static void ChangeCalleesToFastCall(Function *F) {
  1476. for (User *U : F->users()) {
  1477. if (isa<BlockAddress>(U))
  1478. continue;
  1479. cast<CallBase>(U)->setCallingConv(CallingConv::Fast);
  1480. }
  1481. }
  1482. static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs,
  1483. Attribute::AttrKind A) {
  1484. unsigned AttrIndex;
  1485. if (Attrs.hasAttrSomewhere(A, &AttrIndex))
  1486. return Attrs.removeAttributeAtIndex(C, AttrIndex, A);
  1487. return Attrs;
  1488. }
  1489. static void RemoveAttribute(Function *F, Attribute::AttrKind A) {
  1490. F->setAttributes(StripAttr(F->getContext(), F->getAttributes(), A));
  1491. for (User *U : F->users()) {
  1492. if (isa<BlockAddress>(U))
  1493. continue;
  1494. CallBase *CB = cast<CallBase>(U);
  1495. CB->setAttributes(StripAttr(F->getContext(), CB->getAttributes(), A));
  1496. }
  1497. }
  1498. /// Return true if this is a calling convention that we'd like to change. The
  1499. /// idea here is that we don't want to mess with the convention if the user
  1500. /// explicitly requested something with performance implications like coldcc,
  1501. /// GHC, or anyregcc.
  1502. static bool hasChangeableCC(Function *F) {
  1503. CallingConv::ID CC = F->getCallingConv();
  1504. // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
  1505. if (CC != CallingConv::C && CC != CallingConv::X86_ThisCall)
  1506. return false;
  1507. // FIXME: Change CC for the whole chain of musttail calls when possible.
  1508. //
  1509. // Can't change CC of the function that either has musttail calls, or is a
  1510. // musttail callee itself
  1511. for (User *U : F->users()) {
  1512. if (isa<BlockAddress>(U))
  1513. continue;
  1514. CallInst* CI = dyn_cast<CallInst>(U);
  1515. if (!CI)
  1516. continue;
  1517. if (CI->isMustTailCall())
  1518. return false;
  1519. }
  1520. for (BasicBlock &BB : *F)
  1521. if (BB.getTerminatingMustTailCall())
  1522. return false;
  1523. return true;
  1524. }
  1525. /// Return true if the block containing the call site has a BlockFrequency of
  1526. /// less than ColdCCRelFreq% of the entry block.
  1527. static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI) {
  1528. const BranchProbability ColdProb(ColdCCRelFreq, 100);
  1529. auto *CallSiteBB = CB.getParent();
  1530. auto CallSiteFreq = CallerBFI.getBlockFreq(CallSiteBB);
  1531. auto CallerEntryFreq =
  1532. CallerBFI.getBlockFreq(&(CB.getCaller()->getEntryBlock()));
  1533. return CallSiteFreq < CallerEntryFreq * ColdProb;
  1534. }
  1535. // This function checks if the input function F is cold at all call sites. It
  1536. // also looks each call site's containing function, returning false if the
  1537. // caller function contains other non cold calls. The input vector AllCallsCold
  1538. // contains a list of functions that only have call sites in cold blocks.
  1539. static bool
  1540. isValidCandidateForColdCC(Function &F,
  1541. function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
  1542. const std::vector<Function *> &AllCallsCold) {
  1543. if (F.user_empty())
  1544. return false;
  1545. for (User *U : F.users()) {
  1546. if (isa<BlockAddress>(U))
  1547. continue;
  1548. CallBase &CB = cast<CallBase>(*U);
  1549. Function *CallerFunc = CB.getParent()->getParent();
  1550. BlockFrequencyInfo &CallerBFI = GetBFI(*CallerFunc);
  1551. if (!isColdCallSite(CB, CallerBFI))
  1552. return false;
  1553. if (!llvm::is_contained(AllCallsCold, CallerFunc))
  1554. return false;
  1555. }
  1556. return true;
  1557. }
  1558. static void changeCallSitesToColdCC(Function *F) {
  1559. for (User *U : F->users()) {
  1560. if (isa<BlockAddress>(U))
  1561. continue;
  1562. cast<CallBase>(U)->setCallingConv(CallingConv::Cold);
  1563. }
  1564. }
  1565. // This function iterates over all the call instructions in the input Function
  1566. // and checks that all call sites are in cold blocks and are allowed to use the
  1567. // coldcc calling convention.
  1568. static bool
  1569. hasOnlyColdCalls(Function &F,
  1570. function_ref<BlockFrequencyInfo &(Function &)> GetBFI) {
  1571. for (BasicBlock &BB : F) {
  1572. for (Instruction &I : BB) {
  1573. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  1574. // Skip over isline asm instructions since they aren't function calls.
  1575. if (CI->isInlineAsm())
  1576. continue;
  1577. Function *CalledFn = CI->getCalledFunction();
  1578. if (!CalledFn)
  1579. return false;
  1580. if (!CalledFn->hasLocalLinkage())
  1581. return false;
  1582. // Skip over instrinsics since they won't remain as function calls.
  1583. if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic)
  1584. continue;
  1585. // Check if it's valid to use coldcc calling convention.
  1586. if (!hasChangeableCC(CalledFn) || CalledFn->isVarArg() ||
  1587. CalledFn->hasAddressTaken())
  1588. return false;
  1589. BlockFrequencyInfo &CallerBFI = GetBFI(F);
  1590. if (!isColdCallSite(*CI, CallerBFI))
  1591. return false;
  1592. }
  1593. }
  1594. }
  1595. return true;
  1596. }
  1597. static bool hasMustTailCallers(Function *F) {
  1598. for (User *U : F->users()) {
  1599. CallBase *CB = dyn_cast<CallBase>(U);
  1600. if (!CB) {
  1601. assert(isa<BlockAddress>(U) &&
  1602. "Expected either CallBase or BlockAddress");
  1603. continue;
  1604. }
  1605. if (CB->isMustTailCall())
  1606. return true;
  1607. }
  1608. return false;
  1609. }
  1610. static bool hasInvokeCallers(Function *F) {
  1611. for (User *U : F->users())
  1612. if (isa<InvokeInst>(U))
  1613. return true;
  1614. return false;
  1615. }
  1616. static void RemovePreallocated(Function *F) {
  1617. RemoveAttribute(F, Attribute::Preallocated);
  1618. auto *M = F->getParent();
  1619. IRBuilder<> Builder(M->getContext());
  1620. // Cannot modify users() while iterating over it, so make a copy.
  1621. SmallVector<User *, 4> PreallocatedCalls(F->users());
  1622. for (User *U : PreallocatedCalls) {
  1623. CallBase *CB = dyn_cast<CallBase>(U);
  1624. if (!CB)
  1625. continue;
  1626. assert(
  1627. !CB->isMustTailCall() &&
  1628. "Shouldn't call RemotePreallocated() on a musttail preallocated call");
  1629. // Create copy of call without "preallocated" operand bundle.
  1630. SmallVector<OperandBundleDef, 1> OpBundles;
  1631. CB->getOperandBundlesAsDefs(OpBundles);
  1632. CallBase *PreallocatedSetup = nullptr;
  1633. for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) {
  1634. if (It->getTag() == "preallocated") {
  1635. PreallocatedSetup = cast<CallBase>(*It->input_begin());
  1636. OpBundles.erase(It);
  1637. break;
  1638. }
  1639. }
  1640. assert(PreallocatedSetup && "Did not find preallocated bundle");
  1641. uint64_t ArgCount =
  1642. cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue();
  1643. assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) &&
  1644. "Unknown indirect call type");
  1645. CallBase *NewCB = CallBase::Create(CB, OpBundles, CB);
  1646. CB->replaceAllUsesWith(NewCB);
  1647. NewCB->takeName(CB);
  1648. CB->eraseFromParent();
  1649. Builder.SetInsertPoint(PreallocatedSetup);
  1650. auto *StackSave =
  1651. Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stacksave));
  1652. Builder.SetInsertPoint(NewCB->getNextNonDebugInstruction());
  1653. Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackrestore),
  1654. StackSave);
  1655. // Replace @llvm.call.preallocated.arg() with alloca.
  1656. // Cannot modify users() while iterating over it, so make a copy.
  1657. // @llvm.call.preallocated.arg() can be called with the same index multiple
  1658. // times. So for each @llvm.call.preallocated.arg(), we see if we have
  1659. // already created a Value* for the index, and if not, create an alloca and
  1660. // bitcast right after the @llvm.call.preallocated.setup() so that it
  1661. // dominates all uses.
  1662. SmallVector<Value *, 2> ArgAllocas(ArgCount);
  1663. SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users());
  1664. for (auto *User : PreallocatedArgs) {
  1665. auto *UseCall = cast<CallBase>(User);
  1666. assert(UseCall->getCalledFunction()->getIntrinsicID() ==
  1667. Intrinsic::call_preallocated_arg &&
  1668. "preallocated token use was not a llvm.call.preallocated.arg");
  1669. uint64_t AllocArgIndex =
  1670. cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue();
  1671. Value *AllocaReplacement = ArgAllocas[AllocArgIndex];
  1672. if (!AllocaReplacement) {
  1673. auto AddressSpace = UseCall->getType()->getPointerAddressSpace();
  1674. auto *ArgType =
  1675. UseCall->getFnAttr(Attribute::Preallocated).getValueAsType();
  1676. auto *InsertBefore = PreallocatedSetup->getNextNonDebugInstruction();
  1677. Builder.SetInsertPoint(InsertBefore);
  1678. auto *Alloca =
  1679. Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg");
  1680. auto *BitCast = Builder.CreateBitCast(
  1681. Alloca, Type::getInt8PtrTy(M->getContext()), UseCall->getName());
  1682. ArgAllocas[AllocArgIndex] = BitCast;
  1683. AllocaReplacement = BitCast;
  1684. }
  1685. UseCall->replaceAllUsesWith(AllocaReplacement);
  1686. UseCall->eraseFromParent();
  1687. }
  1688. // Remove @llvm.call.preallocated.setup().
  1689. cast<Instruction>(PreallocatedSetup)->eraseFromParent();
  1690. }
  1691. }
  1692. static bool
  1693. OptimizeFunctions(Module &M,
  1694. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1695. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1696. function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
  1697. function_ref<DominatorTree &(Function &)> LookupDomTree,
  1698. SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
  1699. bool Changed = false;
  1700. std::vector<Function *> AllCallsCold;
  1701. for (Function &F : llvm::make_early_inc_range(M))
  1702. if (hasOnlyColdCalls(F, GetBFI))
  1703. AllCallsCold.push_back(&F);
  1704. // Optimize functions.
  1705. for (Function &F : llvm::make_early_inc_range(M)) {
  1706. // Don't perform global opt pass on naked functions; we don't want fast
  1707. // calling conventions for naked functions.
  1708. if (F.hasFnAttribute(Attribute::Naked))
  1709. continue;
  1710. // Functions without names cannot be referenced outside this module.
  1711. if (!F.hasName() && !F.isDeclaration() && !F.hasLocalLinkage())
  1712. F.setLinkage(GlobalValue::InternalLinkage);
  1713. if (deleteIfDead(F, NotDiscardableComdats)) {
  1714. Changed = true;
  1715. continue;
  1716. }
  1717. // LLVM's definition of dominance allows instructions that are cyclic
  1718. // in unreachable blocks, e.g.:
  1719. // %pat = select i1 %condition, @global, i16* %pat
  1720. // because any instruction dominates an instruction in a block that's
  1721. // not reachable from entry.
  1722. // So, remove unreachable blocks from the function, because a) there's
  1723. // no point in analyzing them and b) GlobalOpt should otherwise grow
  1724. // some more complicated logic to break these cycles.
  1725. // Removing unreachable blocks might invalidate the dominator so we
  1726. // recalculate it.
  1727. if (!F.isDeclaration()) {
  1728. if (removeUnreachableBlocks(F)) {
  1729. auto &DT = LookupDomTree(F);
  1730. DT.recalculate(F);
  1731. Changed = true;
  1732. }
  1733. }
  1734. Changed |= processGlobal(F, GetTTI, GetTLI, LookupDomTree);
  1735. if (!F.hasLocalLinkage())
  1736. continue;
  1737. // If we have an inalloca parameter that we can safely remove the
  1738. // inalloca attribute from, do so. This unlocks optimizations that
  1739. // wouldn't be safe in the presence of inalloca.
  1740. // FIXME: We should also hoist alloca affected by this to the entry
  1741. // block if possible.
  1742. if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) &&
  1743. !F.hasAddressTaken() && !hasMustTailCallers(&F)) {
  1744. RemoveAttribute(&F, Attribute::InAlloca);
  1745. Changed = true;
  1746. }
  1747. // FIXME: handle invokes
  1748. // FIXME: handle musttail
  1749. if (F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
  1750. if (!F.hasAddressTaken() && !hasMustTailCallers(&F) &&
  1751. !hasInvokeCallers(&F)) {
  1752. RemovePreallocated(&F);
  1753. Changed = true;
  1754. }
  1755. continue;
  1756. }
  1757. if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) {
  1758. NumInternalFunc++;
  1759. TargetTransformInfo &TTI = GetTTI(F);
  1760. // Change the calling convention to coldcc if either stress testing is
  1761. // enabled or the target would like to use coldcc on functions which are
  1762. // cold at all call sites and the callers contain no other non coldcc
  1763. // calls.
  1764. if (EnableColdCCStressTest ||
  1765. (TTI.useColdCCForColdCall(F) &&
  1766. isValidCandidateForColdCC(F, GetBFI, AllCallsCold))) {
  1767. F.setCallingConv(CallingConv::Cold);
  1768. changeCallSitesToColdCC(&F);
  1769. Changed = true;
  1770. NumColdCC++;
  1771. }
  1772. }
  1773. if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) {
  1774. // If this function has a calling convention worth changing, is not a
  1775. // varargs function, and is only called directly, promote it to use the
  1776. // Fast calling convention.
  1777. F.setCallingConv(CallingConv::Fast);
  1778. ChangeCalleesToFastCall(&F);
  1779. ++NumFastCallFns;
  1780. Changed = true;
  1781. }
  1782. if (F.getAttributes().hasAttrSomewhere(Attribute::Nest) &&
  1783. !F.hasAddressTaken()) {
  1784. // The function is not used by a trampoline intrinsic, so it is safe
  1785. // to remove the 'nest' attribute.
  1786. RemoveAttribute(&F, Attribute::Nest);
  1787. ++NumNestRemoved;
  1788. Changed = true;
  1789. }
  1790. }
  1791. return Changed;
  1792. }
  1793. static bool
  1794. OptimizeGlobalVars(Module &M,
  1795. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  1796. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  1797. function_ref<DominatorTree &(Function &)> LookupDomTree,
  1798. SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
  1799. bool Changed = false;
  1800. for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
  1801. // Global variables without names cannot be referenced outside this module.
  1802. if (!GV.hasName() && !GV.isDeclaration() && !GV.hasLocalLinkage())
  1803. GV.setLinkage(GlobalValue::InternalLinkage);
  1804. // Simplify the initializer.
  1805. if (GV.hasInitializer())
  1806. if (auto *C = dyn_cast<Constant>(GV.getInitializer())) {
  1807. auto &DL = M.getDataLayout();
  1808. // TLI is not used in the case of a Constant, so use default nullptr
  1809. // for that optional parameter, since we don't have a Function to
  1810. // provide GetTLI anyway.
  1811. Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr);
  1812. if (New != C)
  1813. GV.setInitializer(New);
  1814. }
  1815. if (deleteIfDead(GV, NotDiscardableComdats)) {
  1816. Changed = true;
  1817. continue;
  1818. }
  1819. Changed |= processGlobal(GV, GetTTI, GetTLI, LookupDomTree);
  1820. }
  1821. return Changed;
  1822. }
  1823. /// Evaluate static constructors in the function, if we can. Return true if we
  1824. /// can, false otherwise.
  1825. static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
  1826. TargetLibraryInfo *TLI) {
  1827. // Call the function.
  1828. Evaluator Eval(DL, TLI);
  1829. Constant *RetValDummy;
  1830. bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
  1831. SmallVector<Constant*, 0>());
  1832. if (EvalSuccess) {
  1833. ++NumCtorsEvaluated;
  1834. // We succeeded at evaluation: commit the result.
  1835. auto NewInitializers = Eval.getMutatedInitializers();
  1836. LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
  1837. << F->getName() << "' to " << NewInitializers.size()
  1838. << " stores.\n");
  1839. for (const auto &Pair : NewInitializers)
  1840. Pair.first->setInitializer(Pair.second);
  1841. for (GlobalVariable *GV : Eval.getInvariants())
  1842. GV->setConstant(true);
  1843. }
  1844. return EvalSuccess;
  1845. }
  1846. static int compareNames(Constant *const *A, Constant *const *B) {
  1847. Value *AStripped = (*A)->stripPointerCasts();
  1848. Value *BStripped = (*B)->stripPointerCasts();
  1849. return AStripped->getName().compare(BStripped->getName());
  1850. }
  1851. static void setUsedInitializer(GlobalVariable &V,
  1852. const SmallPtrSetImpl<GlobalValue *> &Init) {
  1853. if (Init.empty()) {
  1854. V.eraseFromParent();
  1855. return;
  1856. }
  1857. // Type of pointer to the array of pointers.
  1858. PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
  1859. SmallVector<Constant *, 8> UsedArray;
  1860. for (GlobalValue *GV : Init) {
  1861. Constant *Cast
  1862. = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
  1863. UsedArray.push_back(Cast);
  1864. }
  1865. // Sort to get deterministic order.
  1866. array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
  1867. ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
  1868. Module *M = V.getParent();
  1869. V.removeFromParent();
  1870. GlobalVariable *NV =
  1871. new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
  1872. ConstantArray::get(ATy, UsedArray), "");
  1873. NV->takeName(&V);
  1874. NV->setSection("llvm.metadata");
  1875. delete &V;
  1876. }
  1877. namespace {
  1878. /// An easy to access representation of llvm.used and llvm.compiler.used.
  1879. class LLVMUsed {
  1880. SmallPtrSet<GlobalValue *, 4> Used;
  1881. SmallPtrSet<GlobalValue *, 4> CompilerUsed;
  1882. GlobalVariable *UsedV;
  1883. GlobalVariable *CompilerUsedV;
  1884. public:
  1885. LLVMUsed(Module &M) {
  1886. SmallVector<GlobalValue *, 4> Vec;
  1887. UsedV = collectUsedGlobalVariables(M, Vec, false);
  1888. Used = {Vec.begin(), Vec.end()};
  1889. Vec.clear();
  1890. CompilerUsedV = collectUsedGlobalVariables(M, Vec, true);
  1891. CompilerUsed = {Vec.begin(), Vec.end()};
  1892. }
  1893. using iterator = SmallPtrSet<GlobalValue *, 4>::iterator;
  1894. using used_iterator_range = iterator_range<iterator>;
  1895. iterator usedBegin() { return Used.begin(); }
  1896. iterator usedEnd() { return Used.end(); }
  1897. used_iterator_range used() {
  1898. return used_iterator_range(usedBegin(), usedEnd());
  1899. }
  1900. iterator compilerUsedBegin() { return CompilerUsed.begin(); }
  1901. iterator compilerUsedEnd() { return CompilerUsed.end(); }
  1902. used_iterator_range compilerUsed() {
  1903. return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
  1904. }
  1905. bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
  1906. bool compilerUsedCount(GlobalValue *GV) const {
  1907. return CompilerUsed.count(GV);
  1908. }
  1909. bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
  1910. bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
  1911. bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
  1912. bool compilerUsedInsert(GlobalValue *GV) {
  1913. return CompilerUsed.insert(GV).second;
  1914. }
  1915. void syncVariablesAndSets() {
  1916. if (UsedV)
  1917. setUsedInitializer(*UsedV, Used);
  1918. if (CompilerUsedV)
  1919. setUsedInitializer(*CompilerUsedV, CompilerUsed);
  1920. }
  1921. };
  1922. } // end anonymous namespace
  1923. static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
  1924. if (GA.use_empty()) // No use at all.
  1925. return false;
  1926. assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
  1927. "We should have removed the duplicated "
  1928. "element from llvm.compiler.used");
  1929. if (!GA.hasOneUse())
  1930. // Strictly more than one use. So at least one is not in llvm.used and
  1931. // llvm.compiler.used.
  1932. return true;
  1933. // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
  1934. return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
  1935. }
  1936. static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
  1937. const LLVMUsed &U) {
  1938. unsigned N = 2;
  1939. assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
  1940. "We should have removed the duplicated "
  1941. "element from llvm.compiler.used");
  1942. if (U.usedCount(&V) || U.compilerUsedCount(&V))
  1943. ++N;
  1944. return V.hasNUsesOrMore(N);
  1945. }
  1946. static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
  1947. if (!GA.hasLocalLinkage())
  1948. return true;
  1949. return U.usedCount(&GA) || U.compilerUsedCount(&GA);
  1950. }
  1951. static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
  1952. bool &RenameTarget) {
  1953. RenameTarget = false;
  1954. bool Ret = false;
  1955. if (hasUseOtherThanLLVMUsed(GA, U))
  1956. Ret = true;
  1957. // If the alias is externally visible, we may still be able to simplify it.
  1958. if (!mayHaveOtherReferences(GA, U))
  1959. return Ret;
  1960. // If the aliasee has internal linkage, give it the name and linkage
  1961. // of the alias, and delete the alias. This turns:
  1962. // define internal ... @f(...)
  1963. // @a = alias ... @f
  1964. // into:
  1965. // define ... @a(...)
  1966. Constant *Aliasee = GA.getAliasee();
  1967. GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
  1968. if (!Target->hasLocalLinkage())
  1969. return Ret;
  1970. // Do not perform the transform if multiple aliases potentially target the
  1971. // aliasee. This check also ensures that it is safe to replace the section
  1972. // and other attributes of the aliasee with those of the alias.
  1973. if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
  1974. return Ret;
  1975. RenameTarget = true;
  1976. return true;
  1977. }
  1978. static bool
  1979. OptimizeGlobalAliases(Module &M,
  1980. SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
  1981. bool Changed = false;
  1982. LLVMUsed Used(M);
  1983. for (GlobalValue *GV : Used.used())
  1984. Used.compilerUsedErase(GV);
  1985. // Return whether GV is explicitly or implicitly dso_local and not replaceable
  1986. // by another definition in the current linkage unit.
  1987. auto IsModuleLocal = [](GlobalValue &GV) {
  1988. return !GlobalValue::isInterposableLinkage(GV.getLinkage()) &&
  1989. (GV.isDSOLocal() || GV.isImplicitDSOLocal());
  1990. };
  1991. for (GlobalAlias &J : llvm::make_early_inc_range(M.aliases())) {
  1992. // Aliases without names cannot be referenced outside this module.
  1993. if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage())
  1994. J.setLinkage(GlobalValue::InternalLinkage);
  1995. if (deleteIfDead(J, NotDiscardableComdats)) {
  1996. Changed = true;
  1997. continue;
  1998. }
  1999. // If the alias can change at link time, nothing can be done - bail out.
  2000. if (!IsModuleLocal(J))
  2001. continue;
  2002. Constant *Aliasee = J.getAliasee();
  2003. GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
  2004. // We can't trivially replace the alias with the aliasee if the aliasee is
  2005. // non-trivial in some way. We also can't replace the alias with the aliasee
  2006. // if the aliasee may be preemptible at runtime. On ELF, a non-preemptible
  2007. // alias can be used to access the definition as if preemption did not
  2008. // happen.
  2009. // TODO: Try to handle non-zero GEPs of local aliasees.
  2010. if (!Target || !IsModuleLocal(*Target))
  2011. continue;
  2012. Target->removeDeadConstantUsers();
  2013. // Make all users of the alias use the aliasee instead.
  2014. bool RenameTarget;
  2015. if (!hasUsesToReplace(J, Used, RenameTarget))
  2016. continue;
  2017. J.replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J.getType()));
  2018. ++NumAliasesResolved;
  2019. Changed = true;
  2020. if (RenameTarget) {
  2021. // Give the aliasee the name, linkage and other attributes of the alias.
  2022. Target->takeName(&J);
  2023. Target->setLinkage(J.getLinkage());
  2024. Target->setDSOLocal(J.isDSOLocal());
  2025. Target->setVisibility(J.getVisibility());
  2026. Target->setDLLStorageClass(J.getDLLStorageClass());
  2027. if (Used.usedErase(&J))
  2028. Used.usedInsert(Target);
  2029. if (Used.compilerUsedErase(&J))
  2030. Used.compilerUsedInsert(Target);
  2031. } else if (mayHaveOtherReferences(J, Used))
  2032. continue;
  2033. // Delete the alias.
  2034. M.getAliasList().erase(&J);
  2035. ++NumAliasesRemoved;
  2036. Changed = true;
  2037. }
  2038. Used.syncVariablesAndSets();
  2039. return Changed;
  2040. }
  2041. static Function *
  2042. FindCXAAtExit(Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
  2043. // Hack to get a default TLI before we have actual Function.
  2044. auto FuncIter = M.begin();
  2045. if (FuncIter == M.end())
  2046. return nullptr;
  2047. auto *TLI = &GetTLI(*FuncIter);
  2048. LibFunc F = LibFunc_cxa_atexit;
  2049. if (!TLI->has(F))
  2050. return nullptr;
  2051. Function *Fn = M.getFunction(TLI->getName(F));
  2052. if (!Fn)
  2053. return nullptr;
  2054. // Now get the actual TLI for Fn.
  2055. TLI = &GetTLI(*Fn);
  2056. // Make sure that the function has the correct prototype.
  2057. if (!TLI->getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit)
  2058. return nullptr;
  2059. return Fn;
  2060. }
  2061. /// Returns whether the given function is an empty C++ destructor and can
  2062. /// therefore be eliminated.
  2063. /// Note that we assume that other optimization passes have already simplified
  2064. /// the code so we simply check for 'ret'.
  2065. static bool cxxDtorIsEmpty(const Function &Fn) {
  2066. // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
  2067. // nounwind, but that doesn't seem worth doing.
  2068. if (Fn.isDeclaration())
  2069. return false;
  2070. for (auto &I : Fn.getEntryBlock()) {
  2071. if (I.isDebugOrPseudoInst())
  2072. continue;
  2073. if (isa<ReturnInst>(I))
  2074. return true;
  2075. break;
  2076. }
  2077. return false;
  2078. }
  2079. static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
  2080. /// Itanium C++ ABI p3.3.5:
  2081. ///
  2082. /// After constructing a global (or local static) object, that will require
  2083. /// destruction on exit, a termination function is registered as follows:
  2084. ///
  2085. /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
  2086. ///
  2087. /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
  2088. /// call f(p) when DSO d is unloaded, before all such termination calls
  2089. /// registered before this one. It returns zero if registration is
  2090. /// successful, nonzero on failure.
  2091. // This pass will look for calls to __cxa_atexit where the function is trivial
  2092. // and remove them.
  2093. bool Changed = false;
  2094. for (User *U : llvm::make_early_inc_range(CXAAtExitFn->users())) {
  2095. // We're only interested in calls. Theoretically, we could handle invoke
  2096. // instructions as well, but neither llvm-gcc nor clang generate invokes
  2097. // to __cxa_atexit.
  2098. CallInst *CI = dyn_cast<CallInst>(U);
  2099. if (!CI)
  2100. continue;
  2101. Function *DtorFn =
  2102. dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
  2103. if (!DtorFn || !cxxDtorIsEmpty(*DtorFn))
  2104. continue;
  2105. // Just remove the call.
  2106. CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
  2107. CI->eraseFromParent();
  2108. ++NumCXXDtorsRemoved;
  2109. Changed |= true;
  2110. }
  2111. return Changed;
  2112. }
  2113. static bool optimizeGlobalsInModule(
  2114. Module &M, const DataLayout &DL,
  2115. function_ref<TargetLibraryInfo &(Function &)> GetTLI,
  2116. function_ref<TargetTransformInfo &(Function &)> GetTTI,
  2117. function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
  2118. function_ref<DominatorTree &(Function &)> LookupDomTree) {
  2119. SmallPtrSet<const Comdat *, 8> NotDiscardableComdats;
  2120. bool Changed = false;
  2121. bool LocalChange = true;
  2122. while (LocalChange) {
  2123. LocalChange = false;
  2124. NotDiscardableComdats.clear();
  2125. for (const GlobalVariable &GV : M.globals())
  2126. if (const Comdat *C = GV.getComdat())
  2127. if (!GV.isDiscardableIfUnused() || !GV.use_empty())
  2128. NotDiscardableComdats.insert(C);
  2129. for (Function &F : M)
  2130. if (const Comdat *C = F.getComdat())
  2131. if (!F.isDefTriviallyDead())
  2132. NotDiscardableComdats.insert(C);
  2133. for (GlobalAlias &GA : M.aliases())
  2134. if (const Comdat *C = GA.getComdat())
  2135. if (!GA.isDiscardableIfUnused() || !GA.use_empty())
  2136. NotDiscardableComdats.insert(C);
  2137. // Delete functions that are trivially dead, ccc -> fastcc
  2138. LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree,
  2139. NotDiscardableComdats);
  2140. // Optimize global_ctors list.
  2141. LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) {
  2142. return EvaluateStaticConstructor(F, DL, &GetTLI(*F));
  2143. });
  2144. // Optimize non-address-taken globals.
  2145. LocalChange |= OptimizeGlobalVars(M, GetTTI, GetTLI, LookupDomTree,
  2146. NotDiscardableComdats);
  2147. // Resolve aliases, when possible.
  2148. LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats);
  2149. // Try to remove trivial global destructors if they are not removed
  2150. // already.
  2151. Function *CXAAtExitFn = FindCXAAtExit(M, GetTLI);
  2152. if (CXAAtExitFn)
  2153. LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
  2154. Changed |= LocalChange;
  2155. }
  2156. // TODO: Move all global ctors functions to the end of the module for code
  2157. // layout.
  2158. return Changed;
  2159. }
  2160. PreservedAnalyses GlobalOptPass::run(Module &M, ModuleAnalysisManager &AM) {
  2161. auto &DL = M.getDataLayout();
  2162. auto &FAM =
  2163. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  2164. auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{
  2165. return FAM.getResult<DominatorTreeAnalysis>(F);
  2166. };
  2167. auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
  2168. return FAM.getResult<TargetLibraryAnalysis>(F);
  2169. };
  2170. auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & {
  2171. return FAM.getResult<TargetIRAnalysis>(F);
  2172. };
  2173. auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & {
  2174. return FAM.getResult<BlockFrequencyAnalysis>(F);
  2175. };
  2176. if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree))
  2177. return PreservedAnalyses::all();
  2178. return PreservedAnalyses::none();
  2179. }
  2180. namespace {
  2181. struct GlobalOptLegacyPass : public ModulePass {
  2182. static char ID; // Pass identification, replacement for typeid
  2183. GlobalOptLegacyPass() : ModulePass(ID) {
  2184. initializeGlobalOptLegacyPassPass(*PassRegistry::getPassRegistry());
  2185. }
  2186. bool runOnModule(Module &M) override {
  2187. if (skipModule(M))
  2188. return false;
  2189. auto &DL = M.getDataLayout();
  2190. auto LookupDomTree = [this](Function &F) -> DominatorTree & {
  2191. return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
  2192. };
  2193. auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
  2194. return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  2195. };
  2196. auto GetTTI = [this](Function &F) -> TargetTransformInfo & {
  2197. return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  2198. };
  2199. auto GetBFI = [this](Function &F) -> BlockFrequencyInfo & {
  2200. return this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
  2201. };
  2202. return optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI,
  2203. LookupDomTree);
  2204. }
  2205. void getAnalysisUsage(AnalysisUsage &AU) const override {
  2206. AU.addRequired<TargetLibraryInfoWrapperPass>();
  2207. AU.addRequired<TargetTransformInfoWrapperPass>();
  2208. AU.addRequired<DominatorTreeWrapperPass>();
  2209. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  2210. }
  2211. };
  2212. } // end anonymous namespace
  2213. char GlobalOptLegacyPass::ID = 0;
  2214. INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass, "globalopt",
  2215. "Global Variable Optimizer", false, false)
  2216. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  2217. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  2218. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  2219. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  2220. INITIALIZE_PASS_END(GlobalOptLegacyPass, "globalopt",
  2221. "Global Variable Optimizer", false, false)
  2222. ModulePass *llvm::createGlobalOptimizerPass() {
  2223. return new GlobalOptLegacyPass();
  2224. }