ScalarReplAggregates.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629
  1. //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This transformation implements the well known scalar replacement of
  11. // aggregates transformation. This xform breaks up alloca instructions of
  12. // aggregate type (structure or array) into individual alloca instructions for
  13. // each member (if possible). Then, if possible, it transforms the individual
  14. // alloca instructions into nice clean scalar SSA form.
  15. //
  16. // This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
  17. // often interact, especially for C++ programs. As such, iterating between
  18. // SRoA, then Mem2Reg until we run out of things to promote works well.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #include "llvm/Transforms/Scalar.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/Statistic.h"
  25. #include "llvm/Analysis/AssumptionCache.h"
  26. #include "llvm/Analysis/Loads.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/IR/CallSite.h"
  29. #include "llvm/IR/Constants.h"
  30. #include "llvm/IR/DIBuilder.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/DebugInfo.h"
  33. #include "llvm/IR/DerivedTypes.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/GetElementPtrTypeIterator.h"
  37. #include "llvm/IR/GlobalVariable.h"
  38. #include "llvm/IR/IRBuilder.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/IR/IntrinsicInst.h"
  41. #include "llvm/IR/LLVMContext.h"
  42. #include "llvm/IR/Module.h"
  43. #include "llvm/IR/Operator.h"
  44. #include "llvm/Pass.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Support/MathExtras.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include "llvm/Transforms/Utils/Local.h"
  50. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  51. #include "llvm/Transforms/Utils/SSAUpdater.h"
  52. using namespace llvm;
  53. #define DEBUG_TYPE "scalarrepl"
  54. STATISTIC(NumReplaced, "Number of allocas broken up");
  55. STATISTIC(NumPromoted, "Number of allocas promoted");
  56. STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
  57. STATISTIC(NumConverted, "Number of aggregates converted to scalar");
  58. namespace {
  59. struct SROA : public FunctionPass {
  60. SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
  61. : FunctionPass(ID), HasDomTree(hasDT) {
  62. if (T == -1)
  63. SRThreshold = 128;
  64. else
  65. SRThreshold = T;
  66. if (ST == -1)
  67. StructMemberThreshold = 32;
  68. else
  69. StructMemberThreshold = ST;
  70. if (AT == -1)
  71. ArrayElementThreshold = 8;
  72. else
  73. ArrayElementThreshold = AT;
  74. if (SLT == -1)
  75. // Do not limit the scalar integer load size if no threshold is given.
  76. ScalarLoadThreshold = -1;
  77. else
  78. ScalarLoadThreshold = SLT;
  79. }
  80. bool runOnFunction(Function &F) override;
  81. bool performScalarRepl(Function &F);
  82. bool performPromotion(Function &F);
  83. private:
  84. bool HasDomTree;
  85. /// DeadInsts - Keep track of instructions we have made dead, so that
  86. /// we can remove them after we are done working.
  87. SmallVector<Value*, 32> DeadInsts;
  88. /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
  89. /// information about the uses. All these fields are initialized to false
  90. /// and set to true when something is learned.
  91. struct AllocaInfo {
  92. /// The alloca to promote.
  93. AllocaInst *AI;
  94. /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
  95. /// looping and avoid redundant work.
  96. SmallPtrSet<PHINode*, 8> CheckedPHIs;
  97. /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
  98. bool isUnsafe : 1;
  99. /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
  100. bool isMemCpySrc : 1;
  101. /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
  102. bool isMemCpyDst : 1;
  103. /// hasSubelementAccess - This is true if a subelement of the alloca is
  104. /// ever accessed, or false if the alloca is only accessed with mem
  105. /// intrinsics or load/store that only access the entire alloca at once.
  106. bool hasSubelementAccess : 1;
  107. /// hasALoadOrStore - This is true if there are any loads or stores to it.
  108. /// The alloca may just be accessed with memcpy, for example, which would
  109. /// not set this.
  110. bool hasALoadOrStore : 1;
  111. explicit AllocaInfo(AllocaInst *ai)
  112. : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
  113. hasSubelementAccess(false), hasALoadOrStore(false) {}
  114. };
  115. /// SRThreshold - The maximum alloca size to considered for SROA.
  116. unsigned SRThreshold;
  117. /// StructMemberThreshold - The maximum number of members a struct can
  118. /// contain to be considered for SROA.
  119. unsigned StructMemberThreshold;
  120. /// ArrayElementThreshold - The maximum number of elements an array can
  121. /// have to be considered for SROA.
  122. unsigned ArrayElementThreshold;
  123. /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
  124. /// converting to scalar
  125. unsigned ScalarLoadThreshold;
  126. void MarkUnsafe(AllocaInfo &I, Instruction *User) {
  127. I.isUnsafe = true;
  128. DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
  129. }
  130. bool isSafeAllocaToScalarRepl(AllocaInst *AI);
  131. void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
  132. void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
  133. AllocaInfo &Info);
  134. void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
  135. void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
  136. Type *MemOpType, bool isStore, AllocaInfo &Info,
  137. Instruction *TheAccess, bool AllowWholeAccess);
  138. bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
  139. const DataLayout &DL);
  140. uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset, Type *&IdxTy,
  141. const DataLayout &DL);
  142. void DoScalarReplacement(AllocaInst *AI,
  143. std::vector<AllocaInst*> &WorkList);
  144. void DeleteDeadInstructions();
  145. void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
  146. SmallVectorImpl<AllocaInst *> &NewElts);
  147. void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
  148. SmallVectorImpl<AllocaInst *> &NewElts);
  149. void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
  150. SmallVectorImpl<AllocaInst *> &NewElts);
  151. void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
  152. uint64_t Offset,
  153. SmallVectorImpl<AllocaInst *> &NewElts);
  154. void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
  155. AllocaInst *AI,
  156. SmallVectorImpl<AllocaInst *> &NewElts);
  157. void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
  158. SmallVectorImpl<AllocaInst *> &NewElts);
  159. void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
  160. SmallVectorImpl<AllocaInst *> &NewElts);
  161. bool ShouldAttemptScalarRepl(AllocaInst *AI);
  162. };
  163. // SROA_DT - SROA that uses DominatorTree.
  164. struct SROA_DT : public SROA {
  165. static char ID;
  166. public:
  167. SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
  168. SROA(T, true, ID, ST, AT, SLT) {
  169. initializeSROA_DTPass(*PassRegistry::getPassRegistry());
  170. }
  171. // getAnalysisUsage - This pass does not require any passes, but we know it
  172. // will not alter the CFG, so say so.
  173. void getAnalysisUsage(AnalysisUsage &AU) const override {
  174. AU.addRequired<AssumptionCacheTracker>();
  175. AU.addRequired<DominatorTreeWrapperPass>();
  176. AU.setPreservesCFG();
  177. }
  178. };
  179. // SROA_SSAUp - SROA that uses SSAUpdater.
  180. struct SROA_SSAUp : public SROA {
  181. static char ID;
  182. public:
  183. SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
  184. SROA(T, false, ID, ST, AT, SLT) {
  185. initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
  186. }
  187. // getAnalysisUsage - This pass does not require any passes, but we know it
  188. // will not alter the CFG, so say so.
  189. void getAnalysisUsage(AnalysisUsage &AU) const override {
  190. AU.addRequired<AssumptionCacheTracker>();
  191. AU.setPreservesCFG();
  192. }
  193. };
  194. }
  195. char SROA_DT::ID = 0;
  196. char SROA_SSAUp::ID = 0;
  197. INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
  198. "Scalar Replacement of Aggregates (DT)", false, false)
  199. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  200. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  201. INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
  202. "Scalar Replacement of Aggregates (DT)", false, false)
  203. INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
  204. "Scalar Replacement of Aggregates (SSAUp)", false, false)
  205. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  206. INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
  207. "Scalar Replacement of Aggregates (SSAUp)", false, false)
  208. // Public interface to the ScalarReplAggregates pass
  209. FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
  210. bool UseDomTree,
  211. int StructMemberThreshold,
  212. int ArrayElementThreshold,
  213. int ScalarLoadThreshold) {
  214. if (UseDomTree)
  215. return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
  216. ScalarLoadThreshold);
  217. return new SROA_SSAUp(Threshold, StructMemberThreshold,
  218. ArrayElementThreshold, ScalarLoadThreshold);
  219. }
  220. //===----------------------------------------------------------------------===//
  221. // Convert To Scalar Optimization.
  222. //===----------------------------------------------------------------------===//
  223. namespace {
  224. /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
  225. /// optimization, which scans the uses of an alloca and determines if it can
  226. /// rewrite it in terms of a single new alloca that can be mem2reg'd.
  227. class ConvertToScalarInfo {
  228. /// AllocaSize - The size of the alloca being considered in bytes.
  229. unsigned AllocaSize;
  230. const DataLayout &DL;
  231. unsigned ScalarLoadThreshold;
  232. /// IsNotTrivial - This is set to true if there is some access to the object
  233. /// which means that mem2reg can't promote it.
  234. bool IsNotTrivial;
  235. /// ScalarKind - Tracks the kind of alloca being considered for promotion,
  236. /// computed based on the uses of the alloca rather than the LLVM type system.
  237. enum {
  238. Unknown,
  239. // Accesses via GEPs that are consistent with element access of a vector
  240. // type. This will not be converted into a vector unless there is a later
  241. // access using an actual vector type.
  242. ImplicitVector,
  243. // Accesses via vector operations and GEPs that are consistent with the
  244. // layout of a vector type.
  245. Vector,
  246. // An integer bag-of-bits with bitwise operations for insertion and
  247. // extraction. Any combination of types can be converted into this kind
  248. // of scalar.
  249. Integer
  250. } ScalarKind;
  251. /// VectorTy - This tracks the type that we should promote the vector to if
  252. /// it is possible to turn it into a vector. This starts out null, and if it
  253. /// isn't possible to turn into a vector type, it gets set to VoidTy.
  254. VectorType *VectorTy;
  255. /// HadNonMemTransferAccess - True if there is at least one access to the
  256. /// alloca that is not a MemTransferInst. We don't want to turn structs into
  257. /// large integers unless there is some potential for optimization.
  258. bool HadNonMemTransferAccess;
  259. /// HadDynamicAccess - True if some element of this alloca was dynamic.
  260. /// We don't yet have support for turning a dynamic access into a large
  261. /// integer.
  262. bool HadDynamicAccess;
  263. public:
  264. explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
  265. unsigned SLT)
  266. : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
  267. ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
  268. HadDynamicAccess(false) { }
  269. AllocaInst *TryConvert(AllocaInst *AI);
  270. private:
  271. bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
  272. void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
  273. bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
  274. void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
  275. Value *NonConstantIdx);
  276. Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
  277. uint64_t Offset, Value* NonConstantIdx,
  278. IRBuilder<> &Builder);
  279. Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
  280. uint64_t Offset, Value* NonConstantIdx,
  281. IRBuilder<> &Builder);
  282. };
  283. } // end anonymous namespace.
  284. /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
  285. /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
  286. /// alloca if possible or null if not.
  287. AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
  288. // If we can't convert this scalar, or if mem2reg can trivially do it, bail
  289. // out.
  290. if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
  291. return nullptr;
  292. // If an alloca has only memset / memcpy uses, it may still have an Unknown
  293. // ScalarKind. Treat it as an Integer below.
  294. if (ScalarKind == Unknown)
  295. ScalarKind = Integer;
  296. if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
  297. ScalarKind = Integer;
  298. // If we were able to find a vector type that can handle this with
  299. // insert/extract elements, and if there was at least one use that had
  300. // a vector type, promote this to a vector. We don't want to promote
  301. // random stuff that doesn't use vectors (e.g. <9 x double>) because then
  302. // we just get a lot of insert/extracts. If at least one vector is
  303. // involved, then we probably really do have a union of vector/array.
  304. Type *NewTy;
  305. if (ScalarKind == Vector) {
  306. assert(VectorTy && "Missing type for vector scalar.");
  307. DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
  308. << *VectorTy << '\n');
  309. NewTy = VectorTy; // Use the vector type.
  310. } else {
  311. unsigned BitWidth = AllocaSize * 8;
  312. // Do not convert to scalar integer if the alloca size exceeds the
  313. // scalar load threshold.
  314. if (BitWidth > ScalarLoadThreshold)
  315. return nullptr;
  316. if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
  317. !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
  318. return nullptr;
  319. // Dynamic accesses on integers aren't yet supported. They need us to shift
  320. // by a dynamic amount which could be difficult to work out as we might not
  321. // know whether to use a left or right shift.
  322. if (ScalarKind == Integer && HadDynamicAccess)
  323. return nullptr;
  324. DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
  325. // Create and insert the integer alloca.
  326. NewTy = IntegerType::get(AI->getContext(), BitWidth);
  327. }
  328. AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
  329. AI->getParent()->begin());
  330. ConvertUsesToScalar(AI, NewAI, 0, nullptr);
  331. return NewAI;
  332. }
  333. /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
  334. /// (VectorTy) so far at the offset specified by Offset (which is specified in
  335. /// bytes).
  336. ///
  337. /// There are two cases we handle here:
  338. /// 1) A union of vector types of the same size and potentially its elements.
  339. /// Here we turn element accesses into insert/extract element operations.
  340. /// This promotes a <4 x float> with a store of float to the third element
  341. /// into a <4 x float> that uses insert element.
  342. /// 2) A fully general blob of memory, which we turn into some (potentially
  343. /// large) integer type with extract and insert operations where the loads
  344. /// and stores would mutate the memory. We mark this by setting VectorTy
  345. /// to VoidTy.
  346. void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
  347. uint64_t Offset) {
  348. // If we already decided to turn this into a blob of integer memory, there is
  349. // nothing to be done.
  350. if (ScalarKind == Integer)
  351. return;
  352. // If this could be contributing to a vector, analyze it.
  353. // If the In type is a vector that is the same size as the alloca, see if it
  354. // matches the existing VecTy.
  355. if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
  356. if (MergeInVectorType(VInTy, Offset))
  357. return;
  358. } else if (In->isFloatTy() || In->isDoubleTy() ||
  359. (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
  360. isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
  361. // Full width accesses can be ignored, because they can always be turned
  362. // into bitcasts.
  363. unsigned EltSize = In->getPrimitiveSizeInBits()/8;
  364. if (EltSize == AllocaSize)
  365. return;
  366. // If we're accessing something that could be an element of a vector, see
  367. // if the implied vector agrees with what we already have and if Offset is
  368. // compatible with it.
  369. if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
  370. (!VectorTy || EltSize == VectorTy->getElementType()
  371. ->getPrimitiveSizeInBits()/8)) {
  372. if (!VectorTy) {
  373. ScalarKind = ImplicitVector;
  374. VectorTy = VectorType::get(In, AllocaSize/EltSize);
  375. }
  376. return;
  377. }
  378. }
  379. // Otherwise, we have a case that we can't handle with an optimized vector
  380. // form. We can still turn this into a large integer.
  381. ScalarKind = Integer;
  382. }
  383. /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
  384. /// returning true if the type was successfully merged and false otherwise.
  385. bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
  386. uint64_t Offset) {
  387. if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
  388. // If we're storing/loading a vector of the right size, allow it as a
  389. // vector. If this the first vector we see, remember the type so that
  390. // we know the element size. If this is a subsequent access, ignore it
  391. // even if it is a differing type but the same size. Worst case we can
  392. // bitcast the resultant vectors.
  393. if (!VectorTy)
  394. VectorTy = VInTy;
  395. ScalarKind = Vector;
  396. return true;
  397. }
  398. return false;
  399. }
  400. /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
  401. /// its accesses to a single vector type, return true and set VecTy to
  402. /// the new type. If we could convert the alloca into a single promotable
  403. /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
  404. /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
  405. /// is the current offset from the base of the alloca being analyzed.
  406. ///
  407. /// If we see at least one access to the value that is as a vector type, set the
  408. /// SawVec flag.
  409. bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
  410. Value* NonConstantIdx) {
  411. for (User *U : V->users()) {
  412. Instruction *UI = cast<Instruction>(U);
  413. if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  414. // Don't break volatile loads.
  415. if (!LI->isSimple())
  416. return false;
  417. // Don't touch MMX operations.
  418. if (LI->getType()->isX86_MMXTy())
  419. return false;
  420. HadNonMemTransferAccess = true;
  421. MergeInTypeForLoadOrStore(LI->getType(), Offset);
  422. continue;
  423. }
  424. if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  425. // Storing the pointer, not into the value?
  426. if (SI->getOperand(0) == V || !SI->isSimple()) return false;
  427. // Don't touch MMX operations.
  428. if (SI->getOperand(0)->getType()->isX86_MMXTy())
  429. return false;
  430. HadNonMemTransferAccess = true;
  431. MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
  432. continue;
  433. }
  434. if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
  435. if (!onlyUsedByLifetimeMarkers(BCI))
  436. IsNotTrivial = true; // Can't be mem2reg'd.
  437. if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
  438. return false;
  439. continue;
  440. }
  441. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
  442. // If this is a GEP with a variable indices, we can't handle it.
  443. PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
  444. if (!PtrTy)
  445. return false;
  446. // Compute the offset that this GEP adds to the pointer.
  447. SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
  448. Value *GEPNonConstantIdx = nullptr;
  449. if (!GEP->hasAllConstantIndices()) {
  450. if (!isa<VectorType>(PtrTy->getElementType()))
  451. return false;
  452. if (NonConstantIdx)
  453. return false;
  454. GEPNonConstantIdx = Indices.pop_back_val();
  455. if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
  456. return false;
  457. HadDynamicAccess = true;
  458. } else
  459. GEPNonConstantIdx = NonConstantIdx;
  460. uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
  461. Indices);
  462. // See if all uses can be converted.
  463. if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
  464. return false;
  465. IsNotTrivial = true; // Can't be mem2reg'd.
  466. HadNonMemTransferAccess = true;
  467. continue;
  468. }
  469. // If this is a constant sized memset of a constant value (e.g. 0) we can
  470. // handle it.
  471. if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
  472. // Store to dynamic index.
  473. if (NonConstantIdx)
  474. return false;
  475. // Store of constant value.
  476. if (!isa<ConstantInt>(MSI->getValue()))
  477. return false;
  478. // Store of constant size.
  479. ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
  480. if (!Len)
  481. return false;
  482. // If the size differs from the alloca, we can only convert the alloca to
  483. // an integer bag-of-bits.
  484. // FIXME: This should handle all of the cases that are currently accepted
  485. // as vector element insertions.
  486. if (Len->getZExtValue() != AllocaSize || Offset != 0)
  487. ScalarKind = Integer;
  488. IsNotTrivial = true; // Can't be mem2reg'd.
  489. HadNonMemTransferAccess = true;
  490. continue;
  491. }
  492. // If this is a memcpy or memmove into or out of the whole allocation, we
  493. // can handle it like a load or store of the scalar type.
  494. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
  495. // Store to dynamic index.
  496. if (NonConstantIdx)
  497. return false;
  498. ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
  499. if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
  500. return false;
  501. IsNotTrivial = true; // Can't be mem2reg'd.
  502. continue;
  503. }
  504. // If this is a lifetime intrinsic, we can handle it.
  505. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
  506. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  507. II->getIntrinsicID() == Intrinsic::lifetime_end) {
  508. continue;
  509. }
  510. }
  511. // Otherwise, we cannot handle this!
  512. return false;
  513. }
  514. return true;
  515. }
  516. /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
  517. /// directly. This happens when we are converting an "integer union" to a
  518. /// single integer scalar, or when we are converting a "vector union" to a
  519. /// vector with insert/extractelement instructions.
  520. ///
  521. /// Offset is an offset from the original alloca, in bits that need to be
  522. /// shifted to the right. By the end of this, there should be no uses of Ptr.
  523. void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
  524. uint64_t Offset,
  525. Value* NonConstantIdx) {
  526. while (!Ptr->use_empty()) {
  527. Instruction *User = cast<Instruction>(Ptr->user_back());
  528. if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
  529. ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
  530. CI->eraseFromParent();
  531. continue;
  532. }
  533. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  534. // Compute the offset that this GEP adds to the pointer.
  535. SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
  536. Value* GEPNonConstantIdx = nullptr;
  537. if (!GEP->hasAllConstantIndices()) {
  538. assert(!NonConstantIdx &&
  539. "Dynamic GEP reading from dynamic GEP unsupported");
  540. GEPNonConstantIdx = Indices.pop_back_val();
  541. } else
  542. GEPNonConstantIdx = NonConstantIdx;
  543. uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
  544. Indices);
  545. ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
  546. GEP->eraseFromParent();
  547. continue;
  548. }
  549. IRBuilder<> Builder(User);
  550. if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
  551. // The load is a bit extract from NewAI shifted right by Offset bits.
  552. Value *LoadedVal = Builder.CreateLoad(NewAI);
  553. Value *NewLoadVal
  554. = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
  555. NonConstantIdx, Builder);
  556. LI->replaceAllUsesWith(NewLoadVal);
  557. LI->eraseFromParent();
  558. continue;
  559. }
  560. if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  561. assert(SI->getOperand(0) != Ptr && "Consistency error!");
  562. Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
  563. Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
  564. NonConstantIdx, Builder);
  565. Builder.CreateStore(New, NewAI);
  566. SI->eraseFromParent();
  567. // If the load we just inserted is now dead, then the inserted store
  568. // overwrote the entire thing.
  569. if (Old->use_empty())
  570. Old->eraseFromParent();
  571. continue;
  572. }
  573. // If this is a constant sized memset of a constant value (e.g. 0) we can
  574. // transform it into a store of the expanded constant value.
  575. if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
  576. assert(MSI->getRawDest() == Ptr && "Consistency error!");
  577. assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
  578. int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
  579. if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
  580. unsigned NumBytes = static_cast<unsigned>(SNumBytes);
  581. unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
  582. // Compute the value replicated the right number of times.
  583. APInt APVal(NumBytes*8, Val);
  584. // Splat the value if non-zero.
  585. if (Val)
  586. for (unsigned i = 1; i != NumBytes; ++i)
  587. APVal |= APVal << 8;
  588. Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
  589. Value *New = ConvertScalar_InsertValue(
  590. ConstantInt::get(User->getContext(), APVal),
  591. Old, Offset, nullptr, Builder);
  592. Builder.CreateStore(New, NewAI);
  593. // If the load we just inserted is now dead, then the memset overwrote
  594. // the entire thing.
  595. if (Old->use_empty())
  596. Old->eraseFromParent();
  597. }
  598. MSI->eraseFromParent();
  599. continue;
  600. }
  601. // If this is a memcpy or memmove into or out of the whole allocation, we
  602. // can handle it like a load or store of the scalar type.
  603. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
  604. assert(Offset == 0 && "must be store to start of alloca");
  605. assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
  606. // If the source and destination are both to the same alloca, then this is
  607. // a noop copy-to-self, just delete it. Otherwise, emit a load and store
  608. // as appropriate.
  609. AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, DL, 0));
  610. if (GetUnderlyingObject(MTI->getSource(), DL, 0) != OrigAI) {
  611. // Dest must be OrigAI, change this to be a load from the original
  612. // pointer (bitcasted), then a store to our new alloca.
  613. assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
  614. Value *SrcPtr = MTI->getSource();
  615. PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
  616. PointerType* AIPTy = cast<PointerType>(NewAI->getType());
  617. if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
  618. AIPTy = PointerType::get(AIPTy->getElementType(),
  619. SPTy->getAddressSpace());
  620. }
  621. SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
  622. LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
  623. SrcVal->setAlignment(MTI->getAlignment());
  624. Builder.CreateStore(SrcVal, NewAI);
  625. } else if (GetUnderlyingObject(MTI->getDest(), DL, 0) != OrigAI) {
  626. // Src must be OrigAI, change this to be a load from NewAI then a store
  627. // through the original dest pointer (bitcasted).
  628. assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
  629. LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
  630. PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
  631. PointerType* AIPTy = cast<PointerType>(NewAI->getType());
  632. if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
  633. AIPTy = PointerType::get(AIPTy->getElementType(),
  634. DPTy->getAddressSpace());
  635. }
  636. Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
  637. StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
  638. NewStore->setAlignment(MTI->getAlignment());
  639. } else {
  640. // Noop transfer. Src == Dst
  641. }
  642. MTI->eraseFromParent();
  643. continue;
  644. }
  645. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
  646. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  647. II->getIntrinsicID() == Intrinsic::lifetime_end) {
  648. // There's no need to preserve these, as the resulting alloca will be
  649. // converted to a register anyways.
  650. II->eraseFromParent();
  651. continue;
  652. }
  653. }
  654. llvm_unreachable("Unsupported operation!");
  655. }
  656. }
  657. /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
  658. /// or vector value FromVal, extracting the bits from the offset specified by
  659. /// Offset. This returns the value, which is of type ToType.
  660. ///
  661. /// This happens when we are converting an "integer union" to a single
  662. /// integer scalar, or when we are converting a "vector union" to a vector with
  663. /// insert/extractelement instructions.
  664. ///
  665. /// Offset is an offset from the original alloca, in bits that need to be
  666. /// shifted to the right.
  667. Value *ConvertToScalarInfo::
  668. ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
  669. uint64_t Offset, Value* NonConstantIdx,
  670. IRBuilder<> &Builder) {
  671. // If the load is of the whole new alloca, no conversion is needed.
  672. Type *FromType = FromVal->getType();
  673. if (FromType == ToType && Offset == 0)
  674. return FromVal;
  675. // If the result alloca is a vector type, this is either an element
  676. // access or a bitcast to another vector type of the same size.
  677. if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
  678. unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
  679. unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
  680. if (FromTypeSize == ToTypeSize)
  681. return Builder.CreateBitCast(FromVal, ToType);
  682. // Otherwise it must be an element access.
  683. unsigned Elt = 0;
  684. if (Offset) {
  685. unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
  686. Elt = Offset/EltSize;
  687. assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
  688. }
  689. // Return the element extracted out of it.
  690. Value *Idx;
  691. if (NonConstantIdx) {
  692. if (Elt)
  693. Idx = Builder.CreateAdd(NonConstantIdx,
  694. Builder.getInt32(Elt),
  695. "dyn.offset");
  696. else
  697. Idx = NonConstantIdx;
  698. } else
  699. Idx = Builder.getInt32(Elt);
  700. Value *V = Builder.CreateExtractElement(FromVal, Idx);
  701. if (V->getType() != ToType)
  702. V = Builder.CreateBitCast(V, ToType);
  703. return V;
  704. }
  705. // If ToType is a first class aggregate, extract out each of the pieces and
  706. // use insertvalue's to form the FCA.
  707. if (StructType *ST = dyn_cast<StructType>(ToType)) {
  708. assert(!NonConstantIdx &&
  709. "Dynamic indexing into struct types not supported");
  710. const StructLayout &Layout = *DL.getStructLayout(ST);
  711. Value *Res = UndefValue::get(ST);
  712. for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
  713. Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
  714. Offset+Layout.getElementOffsetInBits(i),
  715. nullptr, Builder);
  716. Res = Builder.CreateInsertValue(Res, Elt, i);
  717. }
  718. return Res;
  719. }
  720. if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
  721. assert(!NonConstantIdx &&
  722. "Dynamic indexing into array types not supported");
  723. uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
  724. Value *Res = UndefValue::get(AT);
  725. for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
  726. Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
  727. Offset+i*EltSize, nullptr,
  728. Builder);
  729. Res = Builder.CreateInsertValue(Res, Elt, i);
  730. }
  731. return Res;
  732. }
  733. // Otherwise, this must be a union that was converted to an integer value.
  734. IntegerType *NTy = cast<IntegerType>(FromVal->getType());
  735. // If this is a big-endian system and the load is narrower than the
  736. // full alloca type, we need to do a shift to get the right bits.
  737. int ShAmt = 0;
  738. if (DL.isBigEndian()) {
  739. // On big-endian machines, the lowest bit is stored at the bit offset
  740. // from the pointer given by getTypeStoreSizeInBits. This matters for
  741. // integers with a bitwidth that is not a multiple of 8.
  742. ShAmt = DL.getTypeStoreSizeInBits(NTy) -
  743. DL.getTypeStoreSizeInBits(ToType) - Offset;
  744. } else {
  745. ShAmt = Offset;
  746. }
  747. // Note: we support negative bitwidths (with shl) which are not defined.
  748. // We do this to support (f.e.) loads off the end of a structure where
  749. // only some bits are used.
  750. if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
  751. FromVal = Builder.CreateLShr(FromVal,
  752. ConstantInt::get(FromVal->getType(), ShAmt));
  753. else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
  754. FromVal = Builder.CreateShl(FromVal,
  755. ConstantInt::get(FromVal->getType(), -ShAmt));
  756. // Finally, unconditionally truncate the integer to the right width.
  757. unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
  758. if (LIBitWidth < NTy->getBitWidth())
  759. FromVal =
  760. Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
  761. LIBitWidth));
  762. else if (LIBitWidth > NTy->getBitWidth())
  763. FromVal =
  764. Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
  765. LIBitWidth));
  766. // If the result is an integer, this is a trunc or bitcast.
  767. if (ToType->isIntegerTy()) {
  768. // Should be done.
  769. } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
  770. // Just do a bitcast, we know the sizes match up.
  771. FromVal = Builder.CreateBitCast(FromVal, ToType);
  772. } else {
  773. // Otherwise must be a pointer.
  774. FromVal = Builder.CreateIntToPtr(FromVal, ToType);
  775. }
  776. assert(FromVal->getType() == ToType && "Didn't convert right?");
  777. return FromVal;
  778. }
  779. /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
  780. /// or vector value "Old" at the offset specified by Offset.
  781. ///
  782. /// This happens when we are converting an "integer union" to a
  783. /// single integer scalar, or when we are converting a "vector union" to a
  784. /// vector with insert/extractelement instructions.
  785. ///
  786. /// Offset is an offset from the original alloca, in bits that need to be
  787. /// shifted to the right.
  788. ///
  789. /// NonConstantIdx is an index value if there was a GEP with a non-constant
  790. /// index value. If this is 0 then all GEPs used to find this insert address
  791. /// are constant.
  792. Value *ConvertToScalarInfo::
  793. ConvertScalar_InsertValue(Value *SV, Value *Old,
  794. uint64_t Offset, Value* NonConstantIdx,
  795. IRBuilder<> &Builder) {
  796. // Convert the stored type to the actual type, shift it left to insert
  797. // then 'or' into place.
  798. Type *AllocaType = Old->getType();
  799. LLVMContext &Context = Old->getContext();
  800. if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
  801. uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
  802. uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
  803. // Changing the whole vector with memset or with an access of a different
  804. // vector type?
  805. if (ValSize == VecSize)
  806. return Builder.CreateBitCast(SV, AllocaType);
  807. // Must be an element insertion.
  808. Type *EltTy = VTy->getElementType();
  809. if (SV->getType() != EltTy)
  810. SV = Builder.CreateBitCast(SV, EltTy);
  811. uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
  812. unsigned Elt = Offset/EltSize;
  813. Value *Idx;
  814. if (NonConstantIdx) {
  815. if (Elt)
  816. Idx = Builder.CreateAdd(NonConstantIdx,
  817. Builder.getInt32(Elt),
  818. "dyn.offset");
  819. else
  820. Idx = NonConstantIdx;
  821. } else
  822. Idx = Builder.getInt32(Elt);
  823. return Builder.CreateInsertElement(Old, SV, Idx);
  824. }
  825. // If SV is a first-class aggregate value, insert each value recursively.
  826. if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
  827. assert(!NonConstantIdx &&
  828. "Dynamic indexing into struct types not supported");
  829. const StructLayout &Layout = *DL.getStructLayout(ST);
  830. for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
  831. Value *Elt = Builder.CreateExtractValue(SV, i);
  832. Old = ConvertScalar_InsertValue(Elt, Old,
  833. Offset+Layout.getElementOffsetInBits(i),
  834. nullptr, Builder);
  835. }
  836. return Old;
  837. }
  838. if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
  839. assert(!NonConstantIdx &&
  840. "Dynamic indexing into array types not supported");
  841. uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
  842. for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
  843. Value *Elt = Builder.CreateExtractValue(SV, i);
  844. Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
  845. Builder);
  846. }
  847. return Old;
  848. }
  849. // If SV is a float, convert it to the appropriate integer type.
  850. // If it is a pointer, do the same.
  851. unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
  852. unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
  853. unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
  854. unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
  855. if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
  856. SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
  857. else if (SV->getType()->isPointerTy())
  858. SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
  859. // Zero extend or truncate the value if needed.
  860. if (SV->getType() != AllocaType) {
  861. if (SV->getType()->getPrimitiveSizeInBits() <
  862. AllocaType->getPrimitiveSizeInBits())
  863. SV = Builder.CreateZExt(SV, AllocaType);
  864. else {
  865. // Truncation may be needed if storing more than the alloca can hold
  866. // (undefined behavior).
  867. SV = Builder.CreateTrunc(SV, AllocaType);
  868. SrcWidth = DestWidth;
  869. SrcStoreWidth = DestStoreWidth;
  870. }
  871. }
  872. // If this is a big-endian system and the store is narrower than the
  873. // full alloca type, we need to do a shift to get the right bits.
  874. int ShAmt = 0;
  875. if (DL.isBigEndian()) {
  876. // On big-endian machines, the lowest bit is stored at the bit offset
  877. // from the pointer given by getTypeStoreSizeInBits. This matters for
  878. // integers with a bitwidth that is not a multiple of 8.
  879. ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
  880. } else {
  881. ShAmt = Offset;
  882. }
  883. // Note: we support negative bitwidths (with shr) which are not defined.
  884. // We do this to support (f.e.) stores off the end of a structure where
  885. // only some bits in the structure are set.
  886. APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
  887. if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
  888. SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
  889. Mask <<= ShAmt;
  890. } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
  891. SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
  892. Mask = Mask.lshr(-ShAmt);
  893. }
  894. // Mask out the bits we are about to insert from the old value, and or
  895. // in the new bits.
  896. if (SrcWidth != DestWidth) {
  897. assert(DestWidth > SrcWidth);
  898. Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
  899. SV = Builder.CreateOr(Old, SV, "ins");
  900. }
  901. return SV;
  902. }
  903. //===----------------------------------------------------------------------===//
  904. // SRoA Driver
  905. //===----------------------------------------------------------------------===//
  906. bool SROA::runOnFunction(Function &F) {
  907. if (skipOptnoneFunction(F))
  908. return false;
  909. bool Changed = performPromotion(F);
  910. while (1) {
  911. bool LocalChange = performScalarRepl(F);
  912. if (!LocalChange) break; // No need to repromote if no scalarrepl
  913. Changed = true;
  914. LocalChange = performPromotion(F);
  915. if (!LocalChange) break; // No need to re-scalarrepl if no promotion
  916. }
  917. return Changed;
  918. }
  919. namespace {
  920. class AllocaPromoter : public LoadAndStorePromoter {
  921. AllocaInst *AI;
  922. DIBuilder *DIB;
  923. SmallVector<DbgDeclareInst *, 4> DDIs;
  924. SmallVector<DbgValueInst *, 4> DVIs;
  925. public:
  926. AllocaPromoter(ArrayRef<Instruction*> Insts, SSAUpdater &S,
  927. DIBuilder *DB)
  928. : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
  929. void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
  930. // Remember which alloca we're promoting (for isInstInList).
  931. this->AI = AI;
  932. if (auto *L = LocalAsMetadata::getIfExists(AI)) {
  933. if (auto *DINode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
  934. for (User *U : DINode->users())
  935. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
  936. DDIs.push_back(DDI);
  937. else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  938. DVIs.push_back(DVI);
  939. }
  940. }
  941. LoadAndStorePromoter::run(Insts);
  942. AI->eraseFromParent();
  943. for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
  944. E = DDIs.end(); I != E; ++I) {
  945. DbgDeclareInst *DDI = *I;
  946. DDI->eraseFromParent();
  947. }
  948. for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
  949. E = DVIs.end(); I != E; ++I) {
  950. DbgValueInst *DVI = *I;
  951. DVI->eraseFromParent();
  952. }
  953. }
  954. bool isInstInList(Instruction *I,
  955. const SmallVectorImpl<Instruction*> &Insts) const override {
  956. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  957. return LI->getOperand(0) == AI;
  958. return cast<StoreInst>(I)->getPointerOperand() == AI;
  959. }
  960. void updateDebugInfo(Instruction *Inst) const override {
  961. for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
  962. E = DDIs.end(); I != E; ++I) {
  963. DbgDeclareInst *DDI = *I;
  964. if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
  965. ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
  966. else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  967. ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
  968. }
  969. for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
  970. E = DVIs.end(); I != E; ++I) {
  971. DbgValueInst *DVI = *I;
  972. Value *Arg = nullptr;
  973. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  974. // If an argument is zero extended then use argument directly. The ZExt
  975. // may be zapped by an optimization pass in future.
  976. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  977. Arg = dyn_cast<Argument>(ZExt->getOperand(0));
  978. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  979. Arg = dyn_cast<Argument>(SExt->getOperand(0));
  980. if (!Arg)
  981. Arg = SI->getOperand(0);
  982. } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  983. Arg = LI->getOperand(0);
  984. } else {
  985. continue;
  986. }
  987. DIB->insertDbgValueIntrinsic(Arg, 0, DVI->getVariable(),
  988. DVI->getExpression(), DVI->getDebugLoc(),
  989. Inst);
  990. }
  991. }
  992. };
  993. } // end anon namespace
  994. /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
  995. /// subsequently loaded can be rewritten to load both input pointers and then
  996. /// select between the result, allowing the load of the alloca to be promoted.
  997. /// From this:
  998. /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
  999. /// %V = load i32* %P2
  1000. /// to:
  1001. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1002. /// %V2 = load i32* %Other
  1003. /// %V = select i1 %cond, i32 %V1, i32 %V2
  1004. ///
  1005. /// We can do this to a select if its only uses are loads and if the operand to
  1006. /// the select can be loaded unconditionally.
  1007. static bool isSafeSelectToSpeculate(SelectInst *SI) {
  1008. const DataLayout &DL = SI->getModule()->getDataLayout();
  1009. bool TDerefable = isDereferenceablePointer(SI->getTrueValue(), DL);
  1010. bool FDerefable = isDereferenceablePointer(SI->getFalseValue(), DL);
  1011. for (User *U : SI->users()) {
  1012. LoadInst *LI = dyn_cast<LoadInst>(U);
  1013. if (!LI || !LI->isSimple()) return false;
  1014. // Both operands to the select need to be dereferencable, either absolutely
  1015. // (e.g. allocas) or at this point because we can see other accesses to it.
  1016. if (!TDerefable &&
  1017. !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
  1018. LI->getAlignment()))
  1019. return false;
  1020. if (!FDerefable &&
  1021. !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
  1022. LI->getAlignment()))
  1023. return false;
  1024. }
  1025. return true;
  1026. }
  1027. /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
  1028. /// subsequently loaded can be rewritten to load both input pointers in the pred
  1029. /// blocks and then PHI the results, allowing the load of the alloca to be
  1030. /// promoted.
  1031. /// From this:
  1032. /// %P2 = phi [i32* %Alloca, i32* %Other]
  1033. /// %V = load i32* %P2
  1034. /// to:
  1035. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1036. /// ...
  1037. /// %V2 = load i32* %Other
  1038. /// ...
  1039. /// %V = phi [i32 %V1, i32 %V2]
  1040. ///
  1041. /// We can do this to a select if its only uses are loads and if the operand to
  1042. /// the select can be loaded unconditionally.
  1043. static bool isSafePHIToSpeculate(PHINode *PN) {
  1044. // For now, we can only do this promotion if the load is in the same block as
  1045. // the PHI, and if there are no stores between the phi and load.
  1046. // TODO: Allow recursive phi users.
  1047. // TODO: Allow stores.
  1048. BasicBlock *BB = PN->getParent();
  1049. unsigned MaxAlign = 0;
  1050. for (User *U : PN->users()) {
  1051. LoadInst *LI = dyn_cast<LoadInst>(U);
  1052. if (!LI || !LI->isSimple()) return false;
  1053. // For now we only allow loads in the same block as the PHI. This is a
  1054. // common case that happens when instcombine merges two loads through a PHI.
  1055. if (LI->getParent() != BB) return false;
  1056. // Ensure that there are no instructions between the PHI and the load that
  1057. // could store.
  1058. for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
  1059. if (BBI->mayWriteToMemory())
  1060. return false;
  1061. MaxAlign = std::max(MaxAlign, LI->getAlignment());
  1062. }
  1063. const DataLayout &DL = PN->getModule()->getDataLayout();
  1064. // Okay, we know that we have one or more loads in the same block as the PHI.
  1065. // We can transform this if it is safe to push the loads into the predecessor
  1066. // blocks. The only thing to watch out for is that we can't put a possibly
  1067. // trapping load in the predecessor if it is a critical edge.
  1068. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1069. BasicBlock *Pred = PN->getIncomingBlock(i);
  1070. Value *InVal = PN->getIncomingValue(i);
  1071. // If the terminator of the predecessor has side-effects (an invoke),
  1072. // there is no safe place to put a load in the predecessor.
  1073. if (Pred->getTerminator()->mayHaveSideEffects())
  1074. return false;
  1075. // If the value is produced by the terminator of the predecessor
  1076. // (an invoke), there is no valid place to put a load in the predecessor.
  1077. if (Pred->getTerminator() == InVal)
  1078. return false;
  1079. // If the predecessor has a single successor, then the edge isn't critical.
  1080. if (Pred->getTerminator()->getNumSuccessors() == 1)
  1081. continue;
  1082. // If this pointer is always safe to load, or if we can prove that there is
  1083. // already a load in the block, then we can move the load to the pred block.
  1084. if (isDereferenceablePointer(InVal, DL) ||
  1085. isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign))
  1086. continue;
  1087. return false;
  1088. }
  1089. return true;
  1090. }
  1091. /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
  1092. /// direct (non-volatile) loads and stores to it. If the alloca is close but
  1093. /// not quite there, this will transform the code to allow promotion. As such,
  1094. /// it is a non-pure predicate.
  1095. static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout &DL) {
  1096. SetVector<Instruction*, SmallVector<Instruction*, 4>,
  1097. SmallPtrSet<Instruction*, 4> > InstsToRewrite;
  1098. for (User *U : AI->users()) {
  1099. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  1100. if (!LI->isSimple())
  1101. return false;
  1102. continue;
  1103. }
  1104. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  1105. if (SI->getOperand(0) == AI || !SI->isSimple())
  1106. return false; // Don't allow a store OF the AI, only INTO the AI.
  1107. continue;
  1108. }
  1109. if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
  1110. // If the condition being selected on is a constant, fold the select, yes
  1111. // this does (rarely) happen early on.
  1112. if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
  1113. Value *Result = SI->getOperand(1+CI->isZero());
  1114. SI->replaceAllUsesWith(Result);
  1115. SI->eraseFromParent();
  1116. // This is very rare and we just scrambled the use list of AI, start
  1117. // over completely.
  1118. return tryToMakeAllocaBePromotable(AI, DL);
  1119. }
  1120. // If it is safe to turn "load (select c, AI, ptr)" into a select of two
  1121. // loads, then we can transform this by rewriting the select.
  1122. if (!isSafeSelectToSpeculate(SI))
  1123. return false;
  1124. InstsToRewrite.insert(SI);
  1125. continue;
  1126. }
  1127. if (PHINode *PN = dyn_cast<PHINode>(U)) {
  1128. if (PN->use_empty()) { // Dead PHIs can be stripped.
  1129. InstsToRewrite.insert(PN);
  1130. continue;
  1131. }
  1132. // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
  1133. // in the pred blocks, then we can transform this by rewriting the PHI.
  1134. if (!isSafePHIToSpeculate(PN))
  1135. return false;
  1136. InstsToRewrite.insert(PN);
  1137. continue;
  1138. }
  1139. if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
  1140. if (onlyUsedByLifetimeMarkers(BCI)) {
  1141. InstsToRewrite.insert(BCI);
  1142. continue;
  1143. }
  1144. }
  1145. return false;
  1146. }
  1147. // If there are no instructions to rewrite, then all uses are load/stores and
  1148. // we're done!
  1149. if (InstsToRewrite.empty())
  1150. return true;
  1151. // If we have instructions that need to be rewritten for this to be promotable
  1152. // take care of it now.
  1153. for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
  1154. if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
  1155. // This could only be a bitcast used by nothing but lifetime intrinsics.
  1156. for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
  1157. I != E;)
  1158. cast<Instruction>(*I++)->eraseFromParent();
  1159. BCI->eraseFromParent();
  1160. continue;
  1161. }
  1162. if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
  1163. // Selects in InstsToRewrite only have load uses. Rewrite each as two
  1164. // loads with a new select.
  1165. while (!SI->use_empty()) {
  1166. LoadInst *LI = cast<LoadInst>(SI->user_back());
  1167. IRBuilder<> Builder(LI);
  1168. LoadInst *TrueLoad =
  1169. Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
  1170. LoadInst *FalseLoad =
  1171. Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
  1172. // Transfer alignment and AA info if present.
  1173. TrueLoad->setAlignment(LI->getAlignment());
  1174. FalseLoad->setAlignment(LI->getAlignment());
  1175. AAMDNodes Tags;
  1176. LI->getAAMetadata(Tags);
  1177. if (Tags) {
  1178. TrueLoad->setAAMetadata(Tags);
  1179. FalseLoad->setAAMetadata(Tags);
  1180. }
  1181. Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
  1182. V->takeName(LI);
  1183. LI->replaceAllUsesWith(V);
  1184. LI->eraseFromParent();
  1185. }
  1186. // Now that all the loads are gone, the select is gone too.
  1187. SI->eraseFromParent();
  1188. continue;
  1189. }
  1190. // Otherwise, we have a PHI node which allows us to push the loads into the
  1191. // predecessors.
  1192. PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
  1193. if (PN->use_empty()) {
  1194. PN->eraseFromParent();
  1195. continue;
  1196. }
  1197. Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
  1198. PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
  1199. PN->getName()+".ld", PN);
  1200. // Get the AA tags and alignment to use from one of the loads. It doesn't
  1201. // matter which one we get and if any differ, it doesn't matter.
  1202. LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
  1203. AAMDNodes AATags;
  1204. SomeLoad->getAAMetadata(AATags);
  1205. unsigned Align = SomeLoad->getAlignment();
  1206. // Rewrite all loads of the PN to use the new PHI.
  1207. while (!PN->use_empty()) {
  1208. LoadInst *LI = cast<LoadInst>(PN->user_back());
  1209. LI->replaceAllUsesWith(NewPN);
  1210. LI->eraseFromParent();
  1211. }
  1212. // Inject loads into all of the pred blocks. Keep track of which blocks we
  1213. // insert them into in case we have multiple edges from the same block.
  1214. DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
  1215. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1216. BasicBlock *Pred = PN->getIncomingBlock(i);
  1217. LoadInst *&Load = InsertedLoads[Pred];
  1218. if (!Load) {
  1219. Load = new LoadInst(PN->getIncomingValue(i),
  1220. PN->getName() + "." + Pred->getName(),
  1221. Pred->getTerminator());
  1222. Load->setAlignment(Align);
  1223. if (AATags) Load->setAAMetadata(AATags);
  1224. }
  1225. NewPN->addIncoming(Load, Pred);
  1226. }
  1227. PN->eraseFromParent();
  1228. }
  1229. ++NumAdjusted;
  1230. return true;
  1231. }
  1232. bool SROA::performPromotion(Function &F) {
  1233. std::vector<AllocaInst*> Allocas;
  1234. const DataLayout &DL = F.getParent()->getDataLayout();
  1235. DominatorTree *DT = nullptr;
  1236. if (HasDomTree)
  1237. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1238. AssumptionCache &AC =
  1239. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1240. BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
  1241. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  1242. bool Changed = false;
  1243. SmallVector<Instruction*, 64> Insts;
  1244. while (1) {
  1245. Allocas.clear();
  1246. // Find allocas that are safe to promote, by looking at all instructions in
  1247. // the entry node
  1248. for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
  1249. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
  1250. if (tryToMakeAllocaBePromotable(AI, DL))
  1251. Allocas.push_back(AI);
  1252. if (Allocas.empty()) break;
  1253. if (HasDomTree)
  1254. PromoteMemToReg(Allocas, *DT, nullptr, &AC);
  1255. else {
  1256. SSAUpdater SSA;
  1257. for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
  1258. AllocaInst *AI = Allocas[i];
  1259. // Build list of instructions to promote.
  1260. for (User *U : AI->users())
  1261. Insts.push_back(cast<Instruction>(U));
  1262. AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
  1263. Insts.clear();
  1264. }
  1265. }
  1266. NumPromoted += Allocas.size();
  1267. Changed = true;
  1268. }
  1269. return Changed;
  1270. }
  1271. /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
  1272. /// SROA. It must be a struct or array type with a small number of elements.
  1273. bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
  1274. Type *T = AI->getAllocatedType();
  1275. // Do not promote any struct that has too many members.
  1276. if (StructType *ST = dyn_cast<StructType>(T))
  1277. return ST->getNumElements() <= StructMemberThreshold;
  1278. // Do not promote any array that has too many elements.
  1279. if (ArrayType *AT = dyn_cast<ArrayType>(T))
  1280. return AT->getNumElements() <= ArrayElementThreshold;
  1281. return false;
  1282. }
  1283. // performScalarRepl - This algorithm is a simple worklist driven algorithm,
  1284. // which runs on all of the alloca instructions in the entry block, removing
  1285. // them if they are only used by getelementptr instructions.
  1286. //
  1287. bool SROA::performScalarRepl(Function &F) {
  1288. std::vector<AllocaInst*> WorkList;
  1289. const DataLayout &DL = F.getParent()->getDataLayout();
  1290. // Scan the entry basic block, adding allocas to the worklist.
  1291. BasicBlock &BB = F.getEntryBlock();
  1292. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
  1293. if (AllocaInst *A = dyn_cast<AllocaInst>(I))
  1294. WorkList.push_back(A);
  1295. // Process the worklist
  1296. bool Changed = false;
  1297. while (!WorkList.empty()) {
  1298. AllocaInst *AI = WorkList.back();
  1299. WorkList.pop_back();
  1300. // Handle dead allocas trivially. These can be formed by SROA'ing arrays
  1301. // with unused elements.
  1302. if (AI->use_empty()) {
  1303. AI->eraseFromParent();
  1304. Changed = true;
  1305. continue;
  1306. }
  1307. // If this alloca is impossible for us to promote, reject it early.
  1308. if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
  1309. continue;
  1310. // Check to see if we can perform the core SROA transformation. We cannot
  1311. // transform the allocation instruction if it is an array allocation
  1312. // (allocations OF arrays are ok though), and an allocation of a scalar
  1313. // value cannot be decomposed at all.
  1314. uint64_t AllocaSize = DL.getTypeAllocSize(AI->getAllocatedType());
  1315. // Do not promote [0 x %struct].
  1316. if (AllocaSize == 0) continue;
  1317. // Do not promote any struct whose size is too big.
  1318. if (AllocaSize > SRThreshold) continue;
  1319. // If the alloca looks like a good candidate for scalar replacement, and if
  1320. // all its users can be transformed, then split up the aggregate into its
  1321. // separate elements.
  1322. if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
  1323. DoScalarReplacement(AI, WorkList);
  1324. Changed = true;
  1325. continue;
  1326. }
  1327. // If we can turn this aggregate value (potentially with casts) into a
  1328. // simple scalar value that can be mem2reg'd into a register value.
  1329. // IsNotTrivial tracks whether this is something that mem2reg could have
  1330. // promoted itself. If so, we don't want to transform it needlessly. Note
  1331. // that we can't just check based on the type: the alloca may be of an i32
  1332. // but that has pointer arithmetic to set byte 3 of it or something.
  1333. if (AllocaInst *NewAI =
  1334. ConvertToScalarInfo((unsigned)AllocaSize, DL, ScalarLoadThreshold)
  1335. .TryConvert(AI)) {
  1336. NewAI->takeName(AI);
  1337. AI->eraseFromParent();
  1338. ++NumConverted;
  1339. Changed = true;
  1340. continue;
  1341. }
  1342. // Otherwise, couldn't process this alloca.
  1343. }
  1344. return Changed;
  1345. }
  1346. /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
  1347. /// predicate, do SROA now.
  1348. void SROA::DoScalarReplacement(AllocaInst *AI,
  1349. std::vector<AllocaInst*> &WorkList) {
  1350. DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
  1351. SmallVector<AllocaInst*, 32> ElementAllocas;
  1352. if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
  1353. ElementAllocas.reserve(ST->getNumContainedTypes());
  1354. for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
  1355. AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
  1356. AI->getAlignment(),
  1357. AI->getName() + "." + Twine(i), AI);
  1358. ElementAllocas.push_back(NA);
  1359. WorkList.push_back(NA); // Add to worklist for recursive processing
  1360. }
  1361. } else {
  1362. ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
  1363. ElementAllocas.reserve(AT->getNumElements());
  1364. Type *ElTy = AT->getElementType();
  1365. for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
  1366. AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
  1367. AI->getName() + "." + Twine(i), AI);
  1368. ElementAllocas.push_back(NA);
  1369. WorkList.push_back(NA); // Add to worklist for recursive processing
  1370. }
  1371. }
  1372. // Now that we have created the new alloca instructions, rewrite all the
  1373. // uses of the old alloca.
  1374. RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
  1375. // Now erase any instructions that were made dead while rewriting the alloca.
  1376. DeleteDeadInstructions();
  1377. AI->eraseFromParent();
  1378. ++NumReplaced;
  1379. }
  1380. /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
  1381. /// recursively including all their operands that become trivially dead.
  1382. void SROA::DeleteDeadInstructions() {
  1383. while (!DeadInsts.empty()) {
  1384. Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
  1385. for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
  1386. if (Instruction *U = dyn_cast<Instruction>(*OI)) {
  1387. // Zero out the operand and see if it becomes trivially dead.
  1388. // (But, don't add allocas to the dead instruction list -- they are
  1389. // already on the worklist and will be deleted separately.)
  1390. *OI = nullptr;
  1391. if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
  1392. DeadInsts.push_back(U);
  1393. }
  1394. I->eraseFromParent();
  1395. }
  1396. }
  1397. /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
  1398. /// performing scalar replacement of alloca AI. The results are flagged in
  1399. /// the Info parameter. Offset indicates the position within AI that is
  1400. /// referenced by this instruction.
  1401. void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
  1402. AllocaInfo &Info) {
  1403. const DataLayout &DL = I->getModule()->getDataLayout();
  1404. for (Use &U : I->uses()) {
  1405. Instruction *User = cast<Instruction>(U.getUser());
  1406. if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
  1407. isSafeForScalarRepl(BC, Offset, Info);
  1408. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
  1409. uint64_t GEPOffset = Offset;
  1410. isSafeGEP(GEPI, GEPOffset, Info);
  1411. if (!Info.isUnsafe)
  1412. isSafeForScalarRepl(GEPI, GEPOffset, Info);
  1413. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
  1414. ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
  1415. if (!Length || Length->isNegative())
  1416. return MarkUnsafe(Info, User);
  1417. isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
  1418. U.getOperandNo() == 0, Info, MI,
  1419. true /*AllowWholeAccess*/);
  1420. } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
  1421. if (!LI->isSimple())
  1422. return MarkUnsafe(Info, User);
  1423. Type *LIType = LI->getType();
  1424. isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
  1425. LI, true /*AllowWholeAccess*/);
  1426. Info.hasALoadOrStore = true;
  1427. } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  1428. // Store is ok if storing INTO the pointer, not storing the pointer
  1429. if (!SI->isSimple() || SI->getOperand(0) == I)
  1430. return MarkUnsafe(Info, User);
  1431. Type *SIType = SI->getOperand(0)->getType();
  1432. isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
  1433. SI, true /*AllowWholeAccess*/);
  1434. Info.hasALoadOrStore = true;
  1435. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
  1436. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  1437. II->getIntrinsicID() != Intrinsic::lifetime_end)
  1438. return MarkUnsafe(Info, User);
  1439. } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
  1440. isSafePHISelectUseForScalarRepl(User, Offset, Info);
  1441. } else {
  1442. return MarkUnsafe(Info, User);
  1443. }
  1444. if (Info.isUnsafe) return;
  1445. }
  1446. }
  1447. /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
  1448. /// derived from the alloca, we can often still split the alloca into elements.
  1449. /// This is useful if we have a large alloca where one element is phi'd
  1450. /// together somewhere: we can SRoA and promote all the other elements even if
  1451. /// we end up not being able to promote this one.
  1452. ///
  1453. /// All we require is that the uses of the PHI do not index into other parts of
  1454. /// the alloca. The most important use case for this is single load and stores
  1455. /// that are PHI'd together, which can happen due to code sinking.
  1456. void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
  1457. AllocaInfo &Info) {
  1458. // If we've already checked this PHI, don't do it again.
  1459. if (PHINode *PN = dyn_cast<PHINode>(I))
  1460. if (!Info.CheckedPHIs.insert(PN).second)
  1461. return;
  1462. const DataLayout &DL = I->getModule()->getDataLayout();
  1463. for (User *U : I->users()) {
  1464. Instruction *UI = cast<Instruction>(U);
  1465. if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
  1466. isSafePHISelectUseForScalarRepl(BC, Offset, Info);
  1467. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
  1468. // Only allow "bitcast" GEPs for simplicity. We could generalize this,
  1469. // but would have to prove that we're staying inside of an element being
  1470. // promoted.
  1471. if (!GEPI->hasAllZeroIndices())
  1472. return MarkUnsafe(Info, UI);
  1473. isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
  1474. } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  1475. if (!LI->isSimple())
  1476. return MarkUnsafe(Info, UI);
  1477. Type *LIType = LI->getType();
  1478. isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
  1479. LI, false /*AllowWholeAccess*/);
  1480. Info.hasALoadOrStore = true;
  1481. } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  1482. // Store is ok if storing INTO the pointer, not storing the pointer
  1483. if (!SI->isSimple() || SI->getOperand(0) == I)
  1484. return MarkUnsafe(Info, UI);
  1485. Type *SIType = SI->getOperand(0)->getType();
  1486. isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
  1487. SI, false /*AllowWholeAccess*/);
  1488. Info.hasALoadOrStore = true;
  1489. } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
  1490. isSafePHISelectUseForScalarRepl(UI, Offset, Info);
  1491. } else {
  1492. return MarkUnsafe(Info, UI);
  1493. }
  1494. if (Info.isUnsafe) return;
  1495. }
  1496. }
  1497. /// isSafeGEP - Check if a GEP instruction can be handled for scalar
  1498. /// replacement. It is safe when all the indices are constant, in-bounds
  1499. /// references, and when the resulting offset corresponds to an element within
  1500. /// the alloca type. The results are flagged in the Info parameter. Upon
  1501. /// return, Offset is adjusted as specified by the GEP indices.
  1502. void SROA::isSafeGEP(GetElementPtrInst *GEPI,
  1503. uint64_t &Offset, AllocaInfo &Info) {
  1504. gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
  1505. if (GEPIt == E)
  1506. return;
  1507. bool NonConstant = false;
  1508. unsigned NonConstantIdxSize = 0;
  1509. // Walk through the GEP type indices, checking the types that this indexes
  1510. // into.
  1511. for (; GEPIt != E; ++GEPIt) {
  1512. // Ignore struct elements, no extra checking needed for these.
  1513. if ((*GEPIt)->isStructTy())
  1514. continue;
  1515. ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
  1516. if (!IdxVal)
  1517. return MarkUnsafe(Info, GEPI);
  1518. }
  1519. // Compute the offset due to this GEP and check if the alloca has a
  1520. // component element at that offset.
  1521. SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
  1522. // If this GEP is non-constant then the last operand must have been a
  1523. // dynamic index into a vector. Pop this now as it has no impact on the
  1524. // constant part of the offset.
  1525. if (NonConstant)
  1526. Indices.pop_back();
  1527. const DataLayout &DL = GEPI->getModule()->getDataLayout();
  1528. Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
  1529. if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, NonConstantIdxSize,
  1530. DL))
  1531. MarkUnsafe(Info, GEPI);
  1532. }
  1533. /// isHomogeneousAggregate - Check if type T is a struct or array containing
  1534. /// elements of the same type (which is always true for arrays). If so,
  1535. /// return true with NumElts and EltTy set to the number of elements and the
  1536. /// element type, respectively.
  1537. static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
  1538. Type *&EltTy) {
  1539. if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
  1540. NumElts = AT->getNumElements();
  1541. EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
  1542. return true;
  1543. }
  1544. if (StructType *ST = dyn_cast<StructType>(T)) {
  1545. NumElts = ST->getNumContainedTypes();
  1546. EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
  1547. for (unsigned n = 1; n < NumElts; ++n) {
  1548. if (ST->getContainedType(n) != EltTy)
  1549. return false;
  1550. }
  1551. return true;
  1552. }
  1553. return false;
  1554. }
  1555. /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
  1556. /// "homogeneous" aggregates with the same element type and number of elements.
  1557. static bool isCompatibleAggregate(Type *T1, Type *T2) {
  1558. if (T1 == T2)
  1559. return true;
  1560. unsigned NumElts1, NumElts2;
  1561. Type *EltTy1, *EltTy2;
  1562. if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
  1563. isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
  1564. NumElts1 == NumElts2 &&
  1565. EltTy1 == EltTy2)
  1566. return true;
  1567. return false;
  1568. }
  1569. /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
  1570. /// alloca or has an offset and size that corresponds to a component element
  1571. /// within it. The offset checked here may have been formed from a GEP with a
  1572. /// pointer bitcasted to a different type.
  1573. ///
  1574. /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
  1575. /// unit. If false, it only allows accesses known to be in a single element.
  1576. void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
  1577. Type *MemOpType, bool isStore,
  1578. AllocaInfo &Info, Instruction *TheAccess,
  1579. bool AllowWholeAccess) {
  1580. const DataLayout &DL = TheAccess->getModule()->getDataLayout();
  1581. // Check if this is a load/store of the entire alloca.
  1582. if (Offset == 0 && AllowWholeAccess &&
  1583. MemSize == DL.getTypeAllocSize(Info.AI->getAllocatedType())) {
  1584. // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
  1585. // loads/stores (which are essentially the same as the MemIntrinsics with
  1586. // regard to copying padding between elements). But, if an alloca is
  1587. // flagged as both a source and destination of such operations, we'll need
  1588. // to check later for padding between elements.
  1589. if (!MemOpType || MemOpType->isIntegerTy()) {
  1590. if (isStore)
  1591. Info.isMemCpyDst = true;
  1592. else
  1593. Info.isMemCpySrc = true;
  1594. return;
  1595. }
  1596. // This is also safe for references using a type that is compatible with
  1597. // the type of the alloca, so that loads/stores can be rewritten using
  1598. // insertvalue/extractvalue.
  1599. if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
  1600. Info.hasSubelementAccess = true;
  1601. return;
  1602. }
  1603. }
  1604. // Check if the offset/size correspond to a component within the alloca type.
  1605. Type *T = Info.AI->getAllocatedType();
  1606. if (TypeHasComponent(T, Offset, MemSize, DL)) {
  1607. Info.hasSubelementAccess = true;
  1608. return;
  1609. }
  1610. return MarkUnsafe(Info, TheAccess);
  1611. }
  1612. /// TypeHasComponent - Return true if T has a component type with the
  1613. /// specified offset and size. If Size is zero, do not check the size.
  1614. bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
  1615. const DataLayout &DL) {
  1616. Type *EltTy;
  1617. uint64_t EltSize;
  1618. if (StructType *ST = dyn_cast<StructType>(T)) {
  1619. const StructLayout *Layout = DL.getStructLayout(ST);
  1620. unsigned EltIdx = Layout->getElementContainingOffset(Offset);
  1621. EltTy = ST->getContainedType(EltIdx);
  1622. EltSize = DL.getTypeAllocSize(EltTy);
  1623. Offset -= Layout->getElementOffset(EltIdx);
  1624. } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
  1625. EltTy = AT->getElementType();
  1626. EltSize = DL.getTypeAllocSize(EltTy);
  1627. if (Offset >= AT->getNumElements() * EltSize)
  1628. return false;
  1629. Offset %= EltSize;
  1630. } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
  1631. EltTy = VT->getElementType();
  1632. EltSize = DL.getTypeAllocSize(EltTy);
  1633. if (Offset >= VT->getNumElements() * EltSize)
  1634. return false;
  1635. Offset %= EltSize;
  1636. } else {
  1637. return false;
  1638. }
  1639. if (Offset == 0 && (Size == 0 || EltSize == Size))
  1640. return true;
  1641. // Check if the component spans multiple elements.
  1642. if (Offset + Size > EltSize)
  1643. return false;
  1644. return TypeHasComponent(EltTy, Offset, Size, DL);
  1645. }
  1646. /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
  1647. /// the instruction I, which references it, to use the separate elements.
  1648. /// Offset indicates the position within AI that is referenced by this
  1649. /// instruction.
  1650. void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
  1651. SmallVectorImpl<AllocaInst *> &NewElts) {
  1652. const DataLayout &DL = I->getModule()->getDataLayout();
  1653. for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
  1654. Use &TheUse = *UI++;
  1655. Instruction *User = cast<Instruction>(TheUse.getUser());
  1656. if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
  1657. RewriteBitCast(BC, AI, Offset, NewElts);
  1658. continue;
  1659. }
  1660. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
  1661. RewriteGEP(GEPI, AI, Offset, NewElts);
  1662. continue;
  1663. }
  1664. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
  1665. ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
  1666. uint64_t MemSize = Length->getZExtValue();
  1667. if (Offset == 0 && MemSize == DL.getTypeAllocSize(AI->getAllocatedType()))
  1668. RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
  1669. // Otherwise the intrinsic can only touch a single element and the
  1670. // address operand will be updated, so nothing else needs to be done.
  1671. continue;
  1672. }
  1673. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
  1674. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  1675. II->getIntrinsicID() == Intrinsic::lifetime_end) {
  1676. RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
  1677. }
  1678. continue;
  1679. }
  1680. if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
  1681. Type *LIType = LI->getType();
  1682. if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
  1683. // Replace:
  1684. // %res = load { i32, i32 }* %alloc
  1685. // with:
  1686. // %load.0 = load i32* %alloc.0
  1687. // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
  1688. // %load.1 = load i32* %alloc.1
  1689. // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
  1690. // (Also works for arrays instead of structs)
  1691. Value *Insert = UndefValue::get(LIType);
  1692. IRBuilder<> Builder(LI);
  1693. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  1694. Value *Load = Builder.CreateLoad(NewElts[i], "load");
  1695. Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
  1696. }
  1697. LI->replaceAllUsesWith(Insert);
  1698. DeadInsts.push_back(LI);
  1699. } else if (LIType->isIntegerTy() &&
  1700. DL.getTypeAllocSize(LIType) ==
  1701. DL.getTypeAllocSize(AI->getAllocatedType())) {
  1702. // If this is a load of the entire alloca to an integer, rewrite it.
  1703. RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
  1704. }
  1705. continue;
  1706. }
  1707. if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  1708. Value *Val = SI->getOperand(0);
  1709. Type *SIType = Val->getType();
  1710. if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
  1711. // Replace:
  1712. // store { i32, i32 } %val, { i32, i32 }* %alloc
  1713. // with:
  1714. // %val.0 = extractvalue { i32, i32 } %val, 0
  1715. // store i32 %val.0, i32* %alloc.0
  1716. // %val.1 = extractvalue { i32, i32 } %val, 1
  1717. // store i32 %val.1, i32* %alloc.1
  1718. // (Also works for arrays instead of structs)
  1719. IRBuilder<> Builder(SI);
  1720. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  1721. Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
  1722. Builder.CreateStore(Extract, NewElts[i]);
  1723. }
  1724. DeadInsts.push_back(SI);
  1725. } else if (SIType->isIntegerTy() &&
  1726. DL.getTypeAllocSize(SIType) ==
  1727. DL.getTypeAllocSize(AI->getAllocatedType())) {
  1728. // If this is a store of the entire alloca from an integer, rewrite it.
  1729. RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
  1730. }
  1731. continue;
  1732. }
  1733. if (isa<SelectInst>(User) || isa<PHINode>(User)) {
  1734. // If we have a PHI user of the alloca itself (as opposed to a GEP or
  1735. // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
  1736. // the new pointer.
  1737. if (!isa<AllocaInst>(I)) continue;
  1738. assert(Offset == 0 && NewElts[0] &&
  1739. "Direct alloca use should have a zero offset");
  1740. // If we have a use of the alloca, we know the derived uses will be
  1741. // utilizing just the first element of the scalarized result. Insert a
  1742. // bitcast of the first alloca before the user as required.
  1743. AllocaInst *NewAI = NewElts[0];
  1744. BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
  1745. NewAI->moveBefore(BCI);
  1746. TheUse = BCI;
  1747. continue;
  1748. }
  1749. }
  1750. }
  1751. /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
  1752. /// and recursively continue updating all of its uses.
  1753. void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
  1754. SmallVectorImpl<AllocaInst *> &NewElts) {
  1755. RewriteForScalarRepl(BC, AI, Offset, NewElts);
  1756. if (BC->getOperand(0) != AI)
  1757. return;
  1758. // The bitcast references the original alloca. Replace its uses with
  1759. // references to the alloca containing offset zero (which is normally at
  1760. // index zero, but might not be in cases involving structs with elements
  1761. // of size zero).
  1762. Type *T = AI->getAllocatedType();
  1763. uint64_t EltOffset = 0;
  1764. Type *IdxTy;
  1765. uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy,
  1766. BC->getModule()->getDataLayout());
  1767. Instruction *Val = NewElts[Idx];
  1768. if (Val->getType() != BC->getDestTy()) {
  1769. Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
  1770. Val->takeName(BC);
  1771. }
  1772. BC->replaceAllUsesWith(Val);
  1773. DeadInsts.push_back(BC);
  1774. }
  1775. /// FindElementAndOffset - Return the index of the element containing Offset
  1776. /// within the specified type, which must be either a struct or an array.
  1777. /// Sets T to the type of the element and Offset to the offset within that
  1778. /// element. IdxTy is set to the type of the index result to be used in a
  1779. /// GEP instruction.
  1780. uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset, Type *&IdxTy,
  1781. const DataLayout &DL) {
  1782. uint64_t Idx = 0;
  1783. if (StructType *ST = dyn_cast<StructType>(T)) {
  1784. const StructLayout *Layout = DL.getStructLayout(ST);
  1785. Idx = Layout->getElementContainingOffset(Offset);
  1786. T = ST->getContainedType(Idx);
  1787. Offset -= Layout->getElementOffset(Idx);
  1788. IdxTy = Type::getInt32Ty(T->getContext());
  1789. return Idx;
  1790. } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
  1791. T = AT->getElementType();
  1792. uint64_t EltSize = DL.getTypeAllocSize(T);
  1793. Idx = Offset / EltSize;
  1794. Offset -= Idx * EltSize;
  1795. IdxTy = Type::getInt64Ty(T->getContext());
  1796. return Idx;
  1797. }
  1798. VectorType *VT = cast<VectorType>(T);
  1799. T = VT->getElementType();
  1800. uint64_t EltSize = DL.getTypeAllocSize(T);
  1801. Idx = Offset / EltSize;
  1802. Offset -= Idx * EltSize;
  1803. IdxTy = Type::getInt64Ty(T->getContext());
  1804. return Idx;
  1805. }
  1806. /// RewriteGEP - Check if this GEP instruction moves the pointer across
  1807. /// elements of the alloca that are being split apart, and if so, rewrite
  1808. /// the GEP to be relative to the new element.
  1809. void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
  1810. SmallVectorImpl<AllocaInst *> &NewElts) {
  1811. uint64_t OldOffset = Offset;
  1812. const DataLayout &DL = GEPI->getModule()->getDataLayout();
  1813. SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
  1814. // If the GEP was dynamic then it must have been a dynamic vector lookup.
  1815. // In this case, it must be the last GEP operand which is dynamic so keep that
  1816. // aside until we've found the constant GEP offset then add it back in at the
  1817. // end.
  1818. Value* NonConstantIdx = nullptr;
  1819. if (!GEPI->hasAllConstantIndices())
  1820. NonConstantIdx = Indices.pop_back_val();
  1821. Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
  1822. RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
  1823. Type *T = AI->getAllocatedType();
  1824. Type *IdxTy;
  1825. uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy, DL);
  1826. if (GEPI->getOperand(0) == AI)
  1827. OldIdx = ~0ULL; // Force the GEP to be rewritten.
  1828. T = AI->getAllocatedType();
  1829. uint64_t EltOffset = Offset;
  1830. uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy, DL);
  1831. // If this GEP does not move the pointer across elements of the alloca
  1832. // being split, then it does not needs to be rewritten.
  1833. if (Idx == OldIdx)
  1834. return;
  1835. Type *i32Ty = Type::getInt32Ty(AI->getContext());
  1836. SmallVector<Value*, 8> NewArgs;
  1837. NewArgs.push_back(Constant::getNullValue(i32Ty));
  1838. while (EltOffset != 0) {
  1839. uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy, DL);
  1840. NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
  1841. }
  1842. if (NonConstantIdx) {
  1843. Type* GepTy = T;
  1844. // This GEP has a dynamic index. We need to add "i32 0" to index through
  1845. // any structs or arrays in the original type until we get to the vector
  1846. // to index.
  1847. while (!isa<VectorType>(GepTy)) {
  1848. NewArgs.push_back(Constant::getNullValue(i32Ty));
  1849. GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
  1850. }
  1851. NewArgs.push_back(NonConstantIdx);
  1852. }
  1853. Instruction *Val = NewElts[Idx];
  1854. if (NewArgs.size() > 1) {
  1855. Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
  1856. Val->takeName(GEPI);
  1857. }
  1858. if (Val->getType() != GEPI->getType())
  1859. Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
  1860. GEPI->replaceAllUsesWith(Val);
  1861. DeadInsts.push_back(GEPI);
  1862. }
  1863. /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
  1864. /// to mark the lifetime of the scalarized memory.
  1865. void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
  1866. uint64_t Offset,
  1867. SmallVectorImpl<AllocaInst *> &NewElts) {
  1868. ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
  1869. // Put matching lifetime markers on everything from Offset up to
  1870. // Offset+OldSize.
  1871. Type *AIType = AI->getAllocatedType();
  1872. const DataLayout &DL = II->getModule()->getDataLayout();
  1873. uint64_t NewOffset = Offset;
  1874. Type *IdxTy;
  1875. uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy, DL);
  1876. IRBuilder<> Builder(II);
  1877. uint64_t Size = OldSize->getLimitedValue();
  1878. if (NewOffset) {
  1879. // Splice the first element and index 'NewOffset' bytes in. SROA will
  1880. // split the alloca again later.
  1881. unsigned AS = AI->getType()->getAddressSpace();
  1882. Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
  1883. V = Builder.CreateGEP(Builder.getInt8Ty(), V, Builder.getInt64(NewOffset));
  1884. IdxTy = NewElts[Idx]->getAllocatedType();
  1885. uint64_t EltSize = DL.getTypeAllocSize(IdxTy) - NewOffset;
  1886. if (EltSize > Size) {
  1887. EltSize = Size;
  1888. Size = 0;
  1889. } else {
  1890. Size -= EltSize;
  1891. }
  1892. if (II->getIntrinsicID() == Intrinsic::lifetime_start)
  1893. Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
  1894. else
  1895. Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
  1896. ++Idx;
  1897. }
  1898. for (; Idx != NewElts.size() && Size; ++Idx) {
  1899. IdxTy = NewElts[Idx]->getAllocatedType();
  1900. uint64_t EltSize = DL.getTypeAllocSize(IdxTy);
  1901. if (EltSize > Size) {
  1902. EltSize = Size;
  1903. Size = 0;
  1904. } else {
  1905. Size -= EltSize;
  1906. }
  1907. if (II->getIntrinsicID() == Intrinsic::lifetime_start)
  1908. Builder.CreateLifetimeStart(NewElts[Idx],
  1909. Builder.getInt64(EltSize));
  1910. else
  1911. Builder.CreateLifetimeEnd(NewElts[Idx],
  1912. Builder.getInt64(EltSize));
  1913. }
  1914. DeadInsts.push_back(II);
  1915. }
  1916. /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
  1917. /// Rewrite it to copy or set the elements of the scalarized memory.
  1918. void
  1919. SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
  1920. AllocaInst *AI,
  1921. SmallVectorImpl<AllocaInst *> &NewElts) {
  1922. // If this is a memcpy/memmove, construct the other pointer as the
  1923. // appropriate type. The "Other" pointer is the pointer that goes to memory
  1924. // that doesn't have anything to do with the alloca that we are promoting. For
  1925. // memset, this Value* stays null.
  1926. Value *OtherPtr = nullptr;
  1927. unsigned MemAlignment = MI->getAlignment();
  1928. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
  1929. if (Inst == MTI->getRawDest())
  1930. OtherPtr = MTI->getRawSource();
  1931. else {
  1932. assert(Inst == MTI->getRawSource());
  1933. OtherPtr = MTI->getRawDest();
  1934. }
  1935. }
  1936. // If there is an other pointer, we want to convert it to the same pointer
  1937. // type as AI has, so we can GEP through it safely.
  1938. if (OtherPtr) {
  1939. unsigned AddrSpace =
  1940. cast<PointerType>(OtherPtr->getType())->getAddressSpace();
  1941. // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
  1942. // optimization, but it's also required to detect the corner case where
  1943. // both pointer operands are referencing the same memory, and where
  1944. // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
  1945. // function is only called for mem intrinsics that access the whole
  1946. // aggregate, so non-zero GEPs are not an issue here.)
  1947. OtherPtr = OtherPtr->stripPointerCasts();
  1948. // Copying the alloca to itself is a no-op: just delete it.
  1949. if (OtherPtr == AI || OtherPtr == NewElts[0]) {
  1950. // This code will run twice for a no-op memcpy -- once for each operand.
  1951. // Put only one reference to MI on the DeadInsts list.
  1952. for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
  1953. E = DeadInsts.end(); I != E; ++I)
  1954. if (*I == MI) return;
  1955. DeadInsts.push_back(MI);
  1956. return;
  1957. }
  1958. // If the pointer is not the right type, insert a bitcast to the right
  1959. // type.
  1960. Type *NewTy =
  1961. PointerType::get(AI->getType()->getElementType(), AddrSpace);
  1962. if (OtherPtr->getType() != NewTy)
  1963. OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
  1964. }
  1965. // Process each element of the aggregate.
  1966. bool SROADest = MI->getRawDest() == Inst;
  1967. Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
  1968. const DataLayout &DL = MI->getModule()->getDataLayout();
  1969. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  1970. // If this is a memcpy/memmove, emit a GEP of the other element address.
  1971. Value *OtherElt = nullptr;
  1972. unsigned OtherEltAlign = MemAlignment;
  1973. if (OtherPtr) {
  1974. Value *Idx[2] = { Zero,
  1975. ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
  1976. OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
  1977. OtherPtr->getName()+"."+Twine(i),
  1978. MI);
  1979. uint64_t EltOffset;
  1980. PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
  1981. Type *OtherTy = OtherPtrTy->getElementType();
  1982. if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
  1983. EltOffset = DL.getStructLayout(ST)->getElementOffset(i);
  1984. } else {
  1985. Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
  1986. EltOffset = DL.getTypeAllocSize(EltTy) * i;
  1987. }
  1988. // The alignment of the other pointer is the guaranteed alignment of the
  1989. // element, which is affected by both the known alignment of the whole
  1990. // mem intrinsic and the alignment of the element. If the alignment of
  1991. // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
  1992. // known alignment is just 4 bytes.
  1993. OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
  1994. }
  1995. Value *EltPtr = NewElts[i];
  1996. Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
  1997. // If we got down to a scalar, insert a load or store as appropriate.
  1998. if (EltTy->isSingleValueType()) {
  1999. if (isa<MemTransferInst>(MI)) {
  2000. if (SROADest) {
  2001. // From Other to Alloca.
  2002. Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
  2003. new StoreInst(Elt, EltPtr, MI);
  2004. } else {
  2005. // From Alloca to Other.
  2006. Value *Elt = new LoadInst(EltPtr, "tmp", MI);
  2007. new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
  2008. }
  2009. continue;
  2010. }
  2011. assert(isa<MemSetInst>(MI));
  2012. // If the stored element is zero (common case), just store a null
  2013. // constant.
  2014. Constant *StoreVal;
  2015. if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
  2016. if (CI->isZero()) {
  2017. StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
  2018. } else {
  2019. // If EltTy is a vector type, get the element type.
  2020. Type *ValTy = EltTy->getScalarType();
  2021. // Construct an integer with the right value.
  2022. unsigned EltSize = DL.getTypeSizeInBits(ValTy);
  2023. APInt OneVal(EltSize, CI->getZExtValue());
  2024. APInt TotalVal(OneVal);
  2025. // Set each byte.
  2026. for (unsigned i = 0; 8*i < EltSize; ++i) {
  2027. TotalVal = TotalVal.shl(8);
  2028. TotalVal |= OneVal;
  2029. }
  2030. // Convert the integer value to the appropriate type.
  2031. StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
  2032. if (ValTy->isPointerTy())
  2033. StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
  2034. else if (ValTy->isFloatingPointTy())
  2035. StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
  2036. assert(StoreVal->getType() == ValTy && "Type mismatch!");
  2037. // If the requested value was a vector constant, create it.
  2038. if (EltTy->isVectorTy()) {
  2039. unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
  2040. StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
  2041. }
  2042. }
  2043. new StoreInst(StoreVal, EltPtr, MI);
  2044. continue;
  2045. }
  2046. // Otherwise, if we're storing a byte variable, use a memset call for
  2047. // this element.
  2048. }
  2049. unsigned EltSize = DL.getTypeAllocSize(EltTy);
  2050. if (!EltSize)
  2051. continue;
  2052. IRBuilder<> Builder(MI);
  2053. // Finally, insert the meminst for this element.
  2054. if (isa<MemSetInst>(MI)) {
  2055. Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
  2056. MI->isVolatile());
  2057. } else {
  2058. assert(isa<MemTransferInst>(MI));
  2059. Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
  2060. Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
  2061. if (isa<MemCpyInst>(MI))
  2062. Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
  2063. else
  2064. Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
  2065. }
  2066. }
  2067. DeadInsts.push_back(MI);
  2068. }
  2069. /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
  2070. /// overwrites the entire allocation. Extract out the pieces of the stored
  2071. /// integer and store them individually.
  2072. void
  2073. SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
  2074. SmallVectorImpl<AllocaInst *> &NewElts) {
  2075. // Extract each element out of the integer according to its structure offset
  2076. // and store the element value to the individual alloca.
  2077. Value *SrcVal = SI->getOperand(0);
  2078. Type *AllocaEltTy = AI->getAllocatedType();
  2079. const DataLayout &DL = SI->getModule()->getDataLayout();
  2080. uint64_t AllocaSizeBits = DL.getTypeAllocSizeInBits(AllocaEltTy);
  2081. IRBuilder<> Builder(SI);
  2082. // Handle tail padding by extending the operand
  2083. if (DL.getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
  2084. SrcVal = Builder.CreateZExt(SrcVal,
  2085. IntegerType::get(SI->getContext(), AllocaSizeBits));
  2086. DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
  2087. << '\n');
  2088. // There are two forms here: AI could be an array or struct. Both cases
  2089. // have different ways to compute the element offset.
  2090. if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
  2091. const StructLayout *Layout = DL.getStructLayout(EltSTy);
  2092. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2093. // Get the number of bits to shift SrcVal to get the value.
  2094. Type *FieldTy = EltSTy->getElementType(i);
  2095. uint64_t Shift = Layout->getElementOffsetInBits(i);
  2096. if (DL.isBigEndian())
  2097. Shift = AllocaSizeBits - Shift - DL.getTypeAllocSizeInBits(FieldTy);
  2098. Value *EltVal = SrcVal;
  2099. if (Shift) {
  2100. Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
  2101. EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
  2102. }
  2103. // Truncate down to an integer of the right size.
  2104. uint64_t FieldSizeBits = DL.getTypeSizeInBits(FieldTy);
  2105. // Ignore zero sized fields like {}, they obviously contain no data.
  2106. if (FieldSizeBits == 0) continue;
  2107. if (FieldSizeBits != AllocaSizeBits)
  2108. EltVal = Builder.CreateTrunc(EltVal,
  2109. IntegerType::get(SI->getContext(), FieldSizeBits));
  2110. Value *DestField = NewElts[i];
  2111. if (EltVal->getType() == FieldTy) {
  2112. // Storing to an integer field of this size, just do it.
  2113. } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
  2114. // Bitcast to the right element type (for fp/vector values).
  2115. EltVal = Builder.CreateBitCast(EltVal, FieldTy);
  2116. } else {
  2117. // Otherwise, bitcast the dest pointer (for aggregates).
  2118. DestField = Builder.CreateBitCast(DestField,
  2119. PointerType::getUnqual(EltVal->getType()));
  2120. }
  2121. new StoreInst(EltVal, DestField, SI);
  2122. }
  2123. } else {
  2124. ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
  2125. Type *ArrayEltTy = ATy->getElementType();
  2126. uint64_t ElementOffset = DL.getTypeAllocSizeInBits(ArrayEltTy);
  2127. uint64_t ElementSizeBits = DL.getTypeSizeInBits(ArrayEltTy);
  2128. uint64_t Shift;
  2129. if (DL.isBigEndian())
  2130. Shift = AllocaSizeBits-ElementOffset;
  2131. else
  2132. Shift = 0;
  2133. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2134. // Ignore zero sized fields like {}, they obviously contain no data.
  2135. if (ElementSizeBits == 0) continue;
  2136. Value *EltVal = SrcVal;
  2137. if (Shift) {
  2138. Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
  2139. EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
  2140. }
  2141. // Truncate down to an integer of the right size.
  2142. if (ElementSizeBits != AllocaSizeBits)
  2143. EltVal = Builder.CreateTrunc(EltVal,
  2144. IntegerType::get(SI->getContext(),
  2145. ElementSizeBits));
  2146. Value *DestField = NewElts[i];
  2147. if (EltVal->getType() == ArrayEltTy) {
  2148. // Storing to an integer field of this size, just do it.
  2149. } else if (ArrayEltTy->isFloatingPointTy() ||
  2150. ArrayEltTy->isVectorTy()) {
  2151. // Bitcast to the right element type (for fp/vector values).
  2152. EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
  2153. } else {
  2154. // Otherwise, bitcast the dest pointer (for aggregates).
  2155. DestField = Builder.CreateBitCast(DestField,
  2156. PointerType::getUnqual(EltVal->getType()));
  2157. }
  2158. new StoreInst(EltVal, DestField, SI);
  2159. if (DL.isBigEndian())
  2160. Shift -= ElementOffset;
  2161. else
  2162. Shift += ElementOffset;
  2163. }
  2164. }
  2165. DeadInsts.push_back(SI);
  2166. }
  2167. /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
  2168. /// an integer. Load the individual pieces to form the aggregate value.
  2169. void
  2170. SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
  2171. SmallVectorImpl<AllocaInst *> &NewElts) {
  2172. // Extract each element out of the NewElts according to its structure offset
  2173. // and form the result value.
  2174. Type *AllocaEltTy = AI->getAllocatedType();
  2175. const DataLayout &DL = LI->getModule()->getDataLayout();
  2176. uint64_t AllocaSizeBits = DL.getTypeAllocSizeInBits(AllocaEltTy);
  2177. DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
  2178. << '\n');
  2179. // There are two forms here: AI could be an array or struct. Both cases
  2180. // have different ways to compute the element offset.
  2181. const StructLayout *Layout = nullptr;
  2182. uint64_t ArrayEltBitOffset = 0;
  2183. if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
  2184. Layout = DL.getStructLayout(EltSTy);
  2185. } else {
  2186. Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
  2187. ArrayEltBitOffset = DL.getTypeAllocSizeInBits(ArrayEltTy);
  2188. }
  2189. Value *ResultVal =
  2190. Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
  2191. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2192. // Load the value from the alloca. If the NewElt is an aggregate, cast
  2193. // the pointer to an integer of the same size before doing the load.
  2194. Value *SrcField = NewElts[i];
  2195. Type *FieldTy =
  2196. cast<PointerType>(SrcField->getType())->getElementType();
  2197. uint64_t FieldSizeBits = DL.getTypeSizeInBits(FieldTy);
  2198. // Ignore zero sized fields like {}, they obviously contain no data.
  2199. if (FieldSizeBits == 0) continue;
  2200. IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
  2201. FieldSizeBits);
  2202. if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
  2203. !FieldTy->isVectorTy())
  2204. SrcField = new BitCastInst(SrcField,
  2205. PointerType::getUnqual(FieldIntTy),
  2206. "", LI);
  2207. SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
  2208. // If SrcField is a fp or vector of the right size but that isn't an
  2209. // integer type, bitcast to an integer so we can shift it.
  2210. if (SrcField->getType() != FieldIntTy)
  2211. SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
  2212. // Zero extend the field to be the same size as the final alloca so that
  2213. // we can shift and insert it.
  2214. if (SrcField->getType() != ResultVal->getType())
  2215. SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
  2216. // Determine the number of bits to shift SrcField.
  2217. uint64_t Shift;
  2218. if (Layout) // Struct case.
  2219. Shift = Layout->getElementOffsetInBits(i);
  2220. else // Array case.
  2221. Shift = i*ArrayEltBitOffset;
  2222. if (DL.isBigEndian())
  2223. Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
  2224. if (Shift) {
  2225. Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
  2226. SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
  2227. }
  2228. // Don't create an 'or x, 0' on the first iteration.
  2229. if (!isa<Constant>(ResultVal) ||
  2230. !cast<Constant>(ResultVal)->isNullValue())
  2231. ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
  2232. else
  2233. ResultVal = SrcField;
  2234. }
  2235. // Handle tail padding by truncating the result
  2236. if (DL.getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
  2237. ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
  2238. LI->replaceAllUsesWith(ResultVal);
  2239. DeadInsts.push_back(LI);
  2240. }
  2241. /// HasPadding - Return true if the specified type has any structure or
  2242. /// alignment padding in between the elements that would be split apart
  2243. /// by SROA; return false otherwise.
  2244. static bool HasPadding(Type *Ty, const DataLayout &DL) {
  2245. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  2246. Ty = ATy->getElementType();
  2247. return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
  2248. }
  2249. // SROA currently handles only Arrays and Structs.
  2250. StructType *STy = cast<StructType>(Ty);
  2251. const StructLayout *SL = DL.getStructLayout(STy);
  2252. unsigned PrevFieldBitOffset = 0;
  2253. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  2254. unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
  2255. // Check to see if there is any padding between this element and the
  2256. // previous one.
  2257. if (i) {
  2258. unsigned PrevFieldEnd =
  2259. PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
  2260. if (PrevFieldEnd < FieldBitOffset)
  2261. return true;
  2262. }
  2263. PrevFieldBitOffset = FieldBitOffset;
  2264. }
  2265. // Check for tail padding.
  2266. if (unsigned EltCount = STy->getNumElements()) {
  2267. unsigned PrevFieldEnd = PrevFieldBitOffset +
  2268. DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
  2269. if (PrevFieldEnd < SL->getSizeInBits())
  2270. return true;
  2271. }
  2272. return false;
  2273. }
  2274. /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
  2275. /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
  2276. /// or 1 if safe after canonicalization has been performed.
  2277. bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
  2278. // Loop over the use list of the alloca. We can only transform it if all of
  2279. // the users are safe to transform.
  2280. AllocaInfo Info(AI);
  2281. isSafeForScalarRepl(AI, 0, Info);
  2282. if (Info.isUnsafe) {
  2283. DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
  2284. return false;
  2285. }
  2286. const DataLayout &DL = AI->getModule()->getDataLayout();
  2287. // Okay, we know all the users are promotable. If the aggregate is a memcpy
  2288. // source and destination, we have to be careful. In particular, the memcpy
  2289. // could be moving around elements that live in structure padding of the LLVM
  2290. // types, but may actually be used. In these cases, we refuse to promote the
  2291. // struct.
  2292. if (Info.isMemCpySrc && Info.isMemCpyDst &&
  2293. HasPadding(AI->getAllocatedType(), DL))
  2294. return false;
  2295. // If the alloca never has an access to just *part* of it, but is accessed
  2296. // via loads and stores, then we should use ConvertToScalarInfo to promote
  2297. // the alloca instead of promoting each piece at a time and inserting fission
  2298. // and fusion code.
  2299. if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
  2300. // If the struct/array just has one element, use basic SRoA.
  2301. if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
  2302. if (ST->getNumElements() > 1) return false;
  2303. } else {
  2304. if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
  2305. return false;
  2306. }
  2307. }
  2308. return true;
  2309. }