PPCFrameLowering.cpp 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700
  1. //===-- PPCFrameLowering.cpp - PPC Frame Information ----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the PPC implementation of TargetFrameLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "MCTargetDesc/PPCPredicates.h"
  13. #include "PPCFrameLowering.h"
  14. #include "PPCInstrBuilder.h"
  15. #include "PPCInstrInfo.h"
  16. #include "PPCMachineFunctionInfo.h"
  17. #include "PPCSubtarget.h"
  18. #include "PPCTargetMachine.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/CodeGen/MachineFrameInfo.h"
  21. #include "llvm/CodeGen/MachineFunction.h"
  22. #include "llvm/CodeGen/MachineInstrBuilder.h"
  23. #include "llvm/CodeGen/MachineModuleInfo.h"
  24. #include "llvm/CodeGen/MachineRegisterInfo.h"
  25. #include "llvm/CodeGen/RegisterScavenging.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/Target/TargetOptions.h"
  28. using namespace llvm;
  29. #define DEBUG_TYPE "framelowering"
  30. STATISTIC(NumPESpillVSR, "Number of spills to vector in prologue");
  31. STATISTIC(NumPEReloadVSR, "Number of reloads from vector in epilogue");
  32. STATISTIC(NumPrologProbed, "Number of prologues probed");
  33. static cl::opt<bool>
  34. EnablePEVectorSpills("ppc-enable-pe-vector-spills",
  35. cl::desc("Enable spills in prologue to vector registers."),
  36. cl::init(false), cl::Hidden);
  37. static unsigned computeReturnSaveOffset(const PPCSubtarget &STI) {
  38. if (STI.isAIXABI())
  39. return STI.isPPC64() ? 16 : 8;
  40. // SVR4 ABI:
  41. return STI.isPPC64() ? 16 : 4;
  42. }
  43. static unsigned computeTOCSaveOffset(const PPCSubtarget &STI) {
  44. if (STI.isAIXABI())
  45. return STI.isPPC64() ? 40 : 20;
  46. return STI.isELFv2ABI() ? 24 : 40;
  47. }
  48. static unsigned computeFramePointerSaveOffset(const PPCSubtarget &STI) {
  49. // First slot in the general register save area.
  50. return STI.isPPC64() ? -8U : -4U;
  51. }
  52. static unsigned computeLinkageSize(const PPCSubtarget &STI) {
  53. if (STI.isAIXABI() || STI.isPPC64())
  54. return (STI.isELFv2ABI() ? 4 : 6) * (STI.isPPC64() ? 8 : 4);
  55. // 32-bit SVR4 ABI:
  56. return 8;
  57. }
  58. static unsigned computeBasePointerSaveOffset(const PPCSubtarget &STI) {
  59. // Third slot in the general purpose register save area.
  60. if (STI.is32BitELFABI() && STI.getTargetMachine().isPositionIndependent())
  61. return -12U;
  62. // Second slot in the general purpose register save area.
  63. return STI.isPPC64() ? -16U : -8U;
  64. }
  65. static unsigned computeCRSaveOffset(const PPCSubtarget &STI) {
  66. return (STI.isAIXABI() && !STI.isPPC64()) ? 4 : 8;
  67. }
  68. PPCFrameLowering::PPCFrameLowering(const PPCSubtarget &STI)
  69. : TargetFrameLowering(TargetFrameLowering::StackGrowsDown,
  70. STI.getPlatformStackAlignment(), 0),
  71. Subtarget(STI), ReturnSaveOffset(computeReturnSaveOffset(Subtarget)),
  72. TOCSaveOffset(computeTOCSaveOffset(Subtarget)),
  73. FramePointerSaveOffset(computeFramePointerSaveOffset(Subtarget)),
  74. LinkageSize(computeLinkageSize(Subtarget)),
  75. BasePointerSaveOffset(computeBasePointerSaveOffset(Subtarget)),
  76. CRSaveOffset(computeCRSaveOffset(Subtarget)) {}
  77. // With the SVR4 ABI, callee-saved registers have fixed offsets on the stack.
  78. const PPCFrameLowering::SpillSlot *PPCFrameLowering::getCalleeSavedSpillSlots(
  79. unsigned &NumEntries) const {
  80. // Floating-point register save area offsets.
  81. #define CALLEE_SAVED_FPRS \
  82. {PPC::F31, -8}, \
  83. {PPC::F30, -16}, \
  84. {PPC::F29, -24}, \
  85. {PPC::F28, -32}, \
  86. {PPC::F27, -40}, \
  87. {PPC::F26, -48}, \
  88. {PPC::F25, -56}, \
  89. {PPC::F24, -64}, \
  90. {PPC::F23, -72}, \
  91. {PPC::F22, -80}, \
  92. {PPC::F21, -88}, \
  93. {PPC::F20, -96}, \
  94. {PPC::F19, -104}, \
  95. {PPC::F18, -112}, \
  96. {PPC::F17, -120}, \
  97. {PPC::F16, -128}, \
  98. {PPC::F15, -136}, \
  99. {PPC::F14, -144}
  100. // 32-bit general purpose register save area offsets shared by ELF and
  101. // AIX. AIX has an extra CSR with r13.
  102. #define CALLEE_SAVED_GPRS32 \
  103. {PPC::R31, -4}, \
  104. {PPC::R30, -8}, \
  105. {PPC::R29, -12}, \
  106. {PPC::R28, -16}, \
  107. {PPC::R27, -20}, \
  108. {PPC::R26, -24}, \
  109. {PPC::R25, -28}, \
  110. {PPC::R24, -32}, \
  111. {PPC::R23, -36}, \
  112. {PPC::R22, -40}, \
  113. {PPC::R21, -44}, \
  114. {PPC::R20, -48}, \
  115. {PPC::R19, -52}, \
  116. {PPC::R18, -56}, \
  117. {PPC::R17, -60}, \
  118. {PPC::R16, -64}, \
  119. {PPC::R15, -68}, \
  120. {PPC::R14, -72}
  121. // 64-bit general purpose register save area offsets.
  122. #define CALLEE_SAVED_GPRS64 \
  123. {PPC::X31, -8}, \
  124. {PPC::X30, -16}, \
  125. {PPC::X29, -24}, \
  126. {PPC::X28, -32}, \
  127. {PPC::X27, -40}, \
  128. {PPC::X26, -48}, \
  129. {PPC::X25, -56}, \
  130. {PPC::X24, -64}, \
  131. {PPC::X23, -72}, \
  132. {PPC::X22, -80}, \
  133. {PPC::X21, -88}, \
  134. {PPC::X20, -96}, \
  135. {PPC::X19, -104}, \
  136. {PPC::X18, -112}, \
  137. {PPC::X17, -120}, \
  138. {PPC::X16, -128}, \
  139. {PPC::X15, -136}, \
  140. {PPC::X14, -144}
  141. // Vector register save area offsets.
  142. #define CALLEE_SAVED_VRS \
  143. {PPC::V31, -16}, \
  144. {PPC::V30, -32}, \
  145. {PPC::V29, -48}, \
  146. {PPC::V28, -64}, \
  147. {PPC::V27, -80}, \
  148. {PPC::V26, -96}, \
  149. {PPC::V25, -112}, \
  150. {PPC::V24, -128}, \
  151. {PPC::V23, -144}, \
  152. {PPC::V22, -160}, \
  153. {PPC::V21, -176}, \
  154. {PPC::V20, -192}
  155. // Note that the offsets here overlap, but this is fixed up in
  156. // processFunctionBeforeFrameFinalized.
  157. static const SpillSlot ELFOffsets32[] = {
  158. CALLEE_SAVED_FPRS,
  159. CALLEE_SAVED_GPRS32,
  160. // CR save area offset. We map each of the nonvolatile CR fields
  161. // to the slot for CR2, which is the first of the nonvolatile CR
  162. // fields to be assigned, so that we only allocate one save slot.
  163. // See PPCRegisterInfo::hasReservedSpillSlot() for more information.
  164. {PPC::CR2, -4},
  165. // VRSAVE save area offset.
  166. {PPC::VRSAVE, -4},
  167. CALLEE_SAVED_VRS,
  168. // SPE register save area (overlaps Vector save area).
  169. {PPC::S31, -8},
  170. {PPC::S30, -16},
  171. {PPC::S29, -24},
  172. {PPC::S28, -32},
  173. {PPC::S27, -40},
  174. {PPC::S26, -48},
  175. {PPC::S25, -56},
  176. {PPC::S24, -64},
  177. {PPC::S23, -72},
  178. {PPC::S22, -80},
  179. {PPC::S21, -88},
  180. {PPC::S20, -96},
  181. {PPC::S19, -104},
  182. {PPC::S18, -112},
  183. {PPC::S17, -120},
  184. {PPC::S16, -128},
  185. {PPC::S15, -136},
  186. {PPC::S14, -144}};
  187. static const SpillSlot ELFOffsets64[] = {
  188. CALLEE_SAVED_FPRS,
  189. CALLEE_SAVED_GPRS64,
  190. // VRSAVE save area offset.
  191. {PPC::VRSAVE, -4},
  192. CALLEE_SAVED_VRS
  193. };
  194. static const SpillSlot AIXOffsets32[] = {CALLEE_SAVED_FPRS,
  195. CALLEE_SAVED_GPRS32,
  196. // Add AIX's extra CSR.
  197. {PPC::R13, -76},
  198. CALLEE_SAVED_VRS};
  199. static const SpillSlot AIXOffsets64[] = {
  200. CALLEE_SAVED_FPRS, CALLEE_SAVED_GPRS64, CALLEE_SAVED_VRS};
  201. if (Subtarget.is64BitELFABI()) {
  202. NumEntries = array_lengthof(ELFOffsets64);
  203. return ELFOffsets64;
  204. }
  205. if (Subtarget.is32BitELFABI()) {
  206. NumEntries = array_lengthof(ELFOffsets32);
  207. return ELFOffsets32;
  208. }
  209. assert(Subtarget.isAIXABI() && "Unexpected ABI.");
  210. if (Subtarget.isPPC64()) {
  211. NumEntries = array_lengthof(AIXOffsets64);
  212. return AIXOffsets64;
  213. }
  214. NumEntries = array_lengthof(AIXOffsets32);
  215. return AIXOffsets32;
  216. }
  217. static bool spillsCR(const MachineFunction &MF) {
  218. const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  219. return FuncInfo->isCRSpilled();
  220. }
  221. static bool hasSpills(const MachineFunction &MF) {
  222. const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  223. return FuncInfo->hasSpills();
  224. }
  225. static bool hasNonRISpills(const MachineFunction &MF) {
  226. const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  227. return FuncInfo->hasNonRISpills();
  228. }
  229. /// MustSaveLR - Return true if this function requires that we save the LR
  230. /// register onto the stack in the prolog and restore it in the epilog of the
  231. /// function.
  232. static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
  233. const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
  234. // We need a save/restore of LR if there is any def of LR (which is
  235. // defined by calls, including the PIC setup sequence), or if there is
  236. // some use of the LR stack slot (e.g. for builtin_return_address).
  237. // (LR comes in 32 and 64 bit versions.)
  238. MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
  239. return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
  240. }
  241. /// determineFrameLayoutAndUpdate - Determine the size of the frame and maximum
  242. /// call frame size. Update the MachineFunction object with the stack size.
  243. uint64_t
  244. PPCFrameLowering::determineFrameLayoutAndUpdate(MachineFunction &MF,
  245. bool UseEstimate) const {
  246. unsigned NewMaxCallFrameSize = 0;
  247. uint64_t FrameSize = determineFrameLayout(MF, UseEstimate,
  248. &NewMaxCallFrameSize);
  249. MF.getFrameInfo().setStackSize(FrameSize);
  250. MF.getFrameInfo().setMaxCallFrameSize(NewMaxCallFrameSize);
  251. return FrameSize;
  252. }
  253. /// determineFrameLayout - Determine the size of the frame and maximum call
  254. /// frame size.
  255. uint64_t
  256. PPCFrameLowering::determineFrameLayout(const MachineFunction &MF,
  257. bool UseEstimate,
  258. unsigned *NewMaxCallFrameSize) const {
  259. const MachineFrameInfo &MFI = MF.getFrameInfo();
  260. const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  261. // Get the number of bytes to allocate from the FrameInfo
  262. uint64_t FrameSize =
  263. UseEstimate ? MFI.estimateStackSize(MF) : MFI.getStackSize();
  264. // Get stack alignments. The frame must be aligned to the greatest of these:
  265. Align TargetAlign = getStackAlign(); // alignment required per the ABI
  266. Align MaxAlign = MFI.getMaxAlign(); // algmt required by data in frame
  267. Align Alignment = std::max(TargetAlign, MaxAlign);
  268. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  269. unsigned LR = RegInfo->getRARegister();
  270. bool DisableRedZone = MF.getFunction().hasFnAttribute(Attribute::NoRedZone);
  271. bool CanUseRedZone = !MFI.hasVarSizedObjects() && // No dynamic alloca.
  272. !MFI.adjustsStack() && // No calls.
  273. !MustSaveLR(MF, LR) && // No need to save LR.
  274. !FI->mustSaveTOC() && // No need to save TOC.
  275. !RegInfo->hasBasePointer(MF); // No special alignment.
  276. // Note: for PPC32 SVR4ABI, we can still generate stackless
  277. // code if all local vars are reg-allocated.
  278. bool FitsInRedZone = FrameSize <= Subtarget.getRedZoneSize();
  279. // Check whether we can skip adjusting the stack pointer (by using red zone)
  280. if (!DisableRedZone && CanUseRedZone && FitsInRedZone) {
  281. // No need for frame
  282. return 0;
  283. }
  284. // Get the maximum call frame size of all the calls.
  285. unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
  286. // Maximum call frame needs to be at least big enough for linkage area.
  287. unsigned minCallFrameSize = getLinkageSize();
  288. maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
  289. // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
  290. // that allocations will be aligned.
  291. if (MFI.hasVarSizedObjects())
  292. maxCallFrameSize = alignTo(maxCallFrameSize, Alignment);
  293. // Update the new max call frame size if the caller passes in a valid pointer.
  294. if (NewMaxCallFrameSize)
  295. *NewMaxCallFrameSize = maxCallFrameSize;
  296. // Include call frame size in total.
  297. FrameSize += maxCallFrameSize;
  298. // Make sure the frame is aligned.
  299. FrameSize = alignTo(FrameSize, Alignment);
  300. return FrameSize;
  301. }
  302. // hasFP - Return true if the specified function actually has a dedicated frame
  303. // pointer register.
  304. bool PPCFrameLowering::hasFP(const MachineFunction &MF) const {
  305. const MachineFrameInfo &MFI = MF.getFrameInfo();
  306. // FIXME: This is pretty much broken by design: hasFP() might be called really
  307. // early, before the stack layout was calculated and thus hasFP() might return
  308. // true or false here depending on the time of call.
  309. return (MFI.getStackSize()) && needsFP(MF);
  310. }
  311. // needsFP - Return true if the specified function should have a dedicated frame
  312. // pointer register. This is true if the function has variable sized allocas or
  313. // if frame pointer elimination is disabled.
  314. bool PPCFrameLowering::needsFP(const MachineFunction &MF) const {
  315. const MachineFrameInfo &MFI = MF.getFrameInfo();
  316. // Naked functions have no stack frame pushed, so we don't have a frame
  317. // pointer.
  318. if (MF.getFunction().hasFnAttribute(Attribute::Naked))
  319. return false;
  320. return MF.getTarget().Options.DisableFramePointerElim(MF) ||
  321. MFI.hasVarSizedObjects() || MFI.hasStackMap() || MFI.hasPatchPoint() ||
  322. MF.exposesReturnsTwice() ||
  323. (MF.getTarget().Options.GuaranteedTailCallOpt &&
  324. MF.getInfo<PPCFunctionInfo>()->hasFastCall());
  325. }
  326. void PPCFrameLowering::replaceFPWithRealFP(MachineFunction &MF) const {
  327. bool is31 = needsFP(MF);
  328. unsigned FPReg = is31 ? PPC::R31 : PPC::R1;
  329. unsigned FP8Reg = is31 ? PPC::X31 : PPC::X1;
  330. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  331. bool HasBP = RegInfo->hasBasePointer(MF);
  332. unsigned BPReg = HasBP ? (unsigned) RegInfo->getBaseRegister(MF) : FPReg;
  333. unsigned BP8Reg = HasBP ? (unsigned) PPC::X30 : FP8Reg;
  334. for (MachineBasicBlock &MBB : MF)
  335. for (MachineBasicBlock::iterator MBBI = MBB.end(); MBBI != MBB.begin();) {
  336. --MBBI;
  337. for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
  338. MachineOperand &MO = MBBI->getOperand(I);
  339. if (!MO.isReg())
  340. continue;
  341. switch (MO.getReg()) {
  342. case PPC::FP:
  343. MO.setReg(FPReg);
  344. break;
  345. case PPC::FP8:
  346. MO.setReg(FP8Reg);
  347. break;
  348. case PPC::BP:
  349. MO.setReg(BPReg);
  350. break;
  351. case PPC::BP8:
  352. MO.setReg(BP8Reg);
  353. break;
  354. }
  355. }
  356. }
  357. }
  358. /* This function will do the following:
  359. - If MBB is an entry or exit block, set SR1 and SR2 to R0 and R12
  360. respectively (defaults recommended by the ABI) and return true
  361. - If MBB is not an entry block, initialize the register scavenger and look
  362. for available registers.
  363. - If the defaults (R0/R12) are available, return true
  364. - If TwoUniqueRegsRequired is set to true, it looks for two unique
  365. registers. Otherwise, look for a single available register.
  366. - If the required registers are found, set SR1 and SR2 and return true.
  367. - If the required registers are not found, set SR2 or both SR1 and SR2 to
  368. PPC::NoRegister and return false.
  369. Note that if both SR1 and SR2 are valid parameters and TwoUniqueRegsRequired
  370. is not set, this function will attempt to find two different registers, but
  371. still return true if only one register is available (and set SR1 == SR2).
  372. */
  373. bool
  374. PPCFrameLowering::findScratchRegister(MachineBasicBlock *MBB,
  375. bool UseAtEnd,
  376. bool TwoUniqueRegsRequired,
  377. Register *SR1,
  378. Register *SR2) const {
  379. RegScavenger RS;
  380. Register R0 = Subtarget.isPPC64() ? PPC::X0 : PPC::R0;
  381. Register R12 = Subtarget.isPPC64() ? PPC::X12 : PPC::R12;
  382. // Set the defaults for the two scratch registers.
  383. if (SR1)
  384. *SR1 = R0;
  385. if (SR2) {
  386. assert (SR1 && "Asking for the second scratch register but not the first?");
  387. *SR2 = R12;
  388. }
  389. // If MBB is an entry or exit block, use R0 and R12 as the scratch registers.
  390. if ((UseAtEnd && MBB->isReturnBlock()) ||
  391. (!UseAtEnd && (&MBB->getParent()->front() == MBB)))
  392. return true;
  393. RS.enterBasicBlock(*MBB);
  394. if (UseAtEnd && !MBB->empty()) {
  395. // The scratch register will be used at the end of the block, so must
  396. // consider all registers used within the block
  397. MachineBasicBlock::iterator MBBI = MBB->getFirstTerminator();
  398. // If no terminator, back iterator up to previous instruction.
  399. if (MBBI == MBB->end())
  400. MBBI = std::prev(MBBI);
  401. if (MBBI != MBB->begin())
  402. RS.forward(MBBI);
  403. }
  404. // If the two registers are available, we're all good.
  405. // Note that we only return here if both R0 and R12 are available because
  406. // although the function may not require two unique registers, it may benefit
  407. // from having two so we should try to provide them.
  408. if (!RS.isRegUsed(R0) && !RS.isRegUsed(R12))
  409. return true;
  410. // Get the list of callee-saved registers for the target.
  411. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  412. const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MBB->getParent());
  413. // Get all the available registers in the block.
  414. BitVector BV = RS.getRegsAvailable(Subtarget.isPPC64() ? &PPC::G8RCRegClass :
  415. &PPC::GPRCRegClass);
  416. // We shouldn't use callee-saved registers as scratch registers as they may be
  417. // available when looking for a candidate block for shrink wrapping but not
  418. // available when the actual prologue/epilogue is being emitted because they
  419. // were added as live-in to the prologue block by PrologueEpilogueInserter.
  420. for (int i = 0; CSRegs[i]; ++i)
  421. BV.reset(CSRegs[i]);
  422. // Set the first scratch register to the first available one.
  423. if (SR1) {
  424. int FirstScratchReg = BV.find_first();
  425. *SR1 = FirstScratchReg == -1 ? (unsigned)PPC::NoRegister : FirstScratchReg;
  426. }
  427. // If there is another one available, set the second scratch register to that.
  428. // Otherwise, set it to either PPC::NoRegister if this function requires two
  429. // or to whatever SR1 is set to if this function doesn't require two.
  430. if (SR2) {
  431. int SecondScratchReg = BV.find_next(*SR1);
  432. if (SecondScratchReg != -1)
  433. *SR2 = SecondScratchReg;
  434. else
  435. *SR2 = TwoUniqueRegsRequired ? Register() : *SR1;
  436. }
  437. // Now that we've done our best to provide both registers, double check
  438. // whether we were unable to provide enough.
  439. if (BV.count() < (TwoUniqueRegsRequired ? 2U : 1U))
  440. return false;
  441. return true;
  442. }
  443. // We need a scratch register for spilling LR and for spilling CR. By default,
  444. // we use two scratch registers to hide latency. However, if only one scratch
  445. // register is available, we can adjust for that by not overlapping the spill
  446. // code. However, if we need to realign the stack (i.e. have a base pointer)
  447. // and the stack frame is large, we need two scratch registers.
  448. // Also, stack probe requires two scratch registers, one for old sp, one for
  449. // large frame and large probe size.
  450. bool
  451. PPCFrameLowering::twoUniqueScratchRegsRequired(MachineBasicBlock *MBB) const {
  452. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  453. MachineFunction &MF = *(MBB->getParent());
  454. bool HasBP = RegInfo->hasBasePointer(MF);
  455. unsigned FrameSize = determineFrameLayout(MF);
  456. int NegFrameSize = -FrameSize;
  457. bool IsLargeFrame = !isInt<16>(NegFrameSize);
  458. MachineFrameInfo &MFI = MF.getFrameInfo();
  459. Align MaxAlign = MFI.getMaxAlign();
  460. bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
  461. const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
  462. return ((IsLargeFrame || !HasRedZone) && HasBP && MaxAlign > 1) ||
  463. TLI.hasInlineStackProbe(MF);
  464. }
  465. bool PPCFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
  466. MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
  467. return findScratchRegister(TmpMBB, false,
  468. twoUniqueScratchRegsRequired(TmpMBB));
  469. }
  470. bool PPCFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
  471. MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
  472. return findScratchRegister(TmpMBB, true);
  473. }
  474. bool PPCFrameLowering::stackUpdateCanBeMoved(MachineFunction &MF) const {
  475. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  476. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  477. // Abort if there is no register info or function info.
  478. if (!RegInfo || !FI)
  479. return false;
  480. // Only move the stack update on ELFv2 ABI and PPC64.
  481. if (!Subtarget.isELFv2ABI() || !Subtarget.isPPC64())
  482. return false;
  483. // Check the frame size first and return false if it does not fit the
  484. // requirements.
  485. // We need a non-zero frame size as well as a frame that will fit in the red
  486. // zone. This is because by moving the stack pointer update we are now storing
  487. // to the red zone until the stack pointer is updated. If we get an interrupt
  488. // inside the prologue but before the stack update we now have a number of
  489. // stores to the red zone and those stores must all fit.
  490. MachineFrameInfo &MFI = MF.getFrameInfo();
  491. unsigned FrameSize = MFI.getStackSize();
  492. if (!FrameSize || FrameSize > Subtarget.getRedZoneSize())
  493. return false;
  494. // Frame pointers and base pointers complicate matters so don't do anything
  495. // if we have them. For example having a frame pointer will sometimes require
  496. // a copy of r1 into r31 and that makes keeping track of updates to r1 more
  497. // difficult. Similar situation exists with setjmp.
  498. if (hasFP(MF) || RegInfo->hasBasePointer(MF) || MF.exposesReturnsTwice())
  499. return false;
  500. // Calls to fast_cc functions use different rules for passing parameters on
  501. // the stack from the ABI and using PIC base in the function imposes
  502. // similar restrictions to using the base pointer. It is not generally safe
  503. // to move the stack pointer update in these situations.
  504. if (FI->hasFastCall() || FI->usesPICBase())
  505. return false;
  506. // Finally we can move the stack update if we do not require register
  507. // scavenging. Register scavenging can introduce more spills and so
  508. // may make the frame size larger than we have computed.
  509. return !RegInfo->requiresFrameIndexScavenging(MF);
  510. }
  511. void PPCFrameLowering::emitPrologue(MachineFunction &MF,
  512. MachineBasicBlock &MBB) const {
  513. MachineBasicBlock::iterator MBBI = MBB.begin();
  514. MachineFrameInfo &MFI = MF.getFrameInfo();
  515. const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
  516. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  517. const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
  518. MachineModuleInfo &MMI = MF.getMMI();
  519. const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
  520. DebugLoc dl;
  521. // AIX assembler does not support cfi directives.
  522. const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();
  523. // Get processor type.
  524. bool isPPC64 = Subtarget.isPPC64();
  525. // Get the ABI.
  526. bool isSVR4ABI = Subtarget.isSVR4ABI();
  527. bool isELFv2ABI = Subtarget.isELFv2ABI();
  528. assert((isSVR4ABI || Subtarget.isAIXABI()) && "Unsupported PPC ABI.");
  529. // Work out frame sizes.
  530. uint64_t FrameSize = determineFrameLayoutAndUpdate(MF);
  531. int64_t NegFrameSize = -FrameSize;
  532. if (!isInt<32>(FrameSize) || !isInt<32>(NegFrameSize))
  533. llvm_unreachable("Unhandled stack size!");
  534. if (MFI.isFrameAddressTaken())
  535. replaceFPWithRealFP(MF);
  536. // Check if the link register (LR) must be saved.
  537. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  538. bool MustSaveLR = FI->mustSaveLR();
  539. bool MustSaveTOC = FI->mustSaveTOC();
  540. const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
  541. bool MustSaveCR = !MustSaveCRs.empty();
  542. // Do we have a frame pointer and/or base pointer for this function?
  543. bool HasFP = hasFP(MF);
  544. bool HasBP = RegInfo->hasBasePointer(MF);
  545. bool HasRedZone = isPPC64 || !isSVR4ABI;
  546. bool HasROPProtect = Subtarget.hasROPProtect();
  547. bool HasPrivileged = Subtarget.hasPrivileged();
  548. Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
  549. Register BPReg = RegInfo->getBaseRegister(MF);
  550. Register FPReg = isPPC64 ? PPC::X31 : PPC::R31;
  551. Register LRReg = isPPC64 ? PPC::LR8 : PPC::LR;
  552. Register TOCReg = isPPC64 ? PPC::X2 : PPC::R2;
  553. Register ScratchReg;
  554. Register TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
  555. // ...(R12/X12 is volatile in both Darwin & SVR4, & can't be a function arg.)
  556. const MCInstrDesc& MFLRInst = TII.get(isPPC64 ? PPC::MFLR8
  557. : PPC::MFLR );
  558. const MCInstrDesc& StoreInst = TII.get(isPPC64 ? PPC::STD
  559. : PPC::STW );
  560. const MCInstrDesc& StoreUpdtInst = TII.get(isPPC64 ? PPC::STDU
  561. : PPC::STWU );
  562. const MCInstrDesc& StoreUpdtIdxInst = TII.get(isPPC64 ? PPC::STDUX
  563. : PPC::STWUX);
  564. const MCInstrDesc& LoadImmShiftedInst = TII.get(isPPC64 ? PPC::LIS8
  565. : PPC::LIS );
  566. const MCInstrDesc& OrImmInst = TII.get(isPPC64 ? PPC::ORI8
  567. : PPC::ORI );
  568. const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
  569. : PPC::OR );
  570. const MCInstrDesc& SubtractCarryingInst = TII.get(isPPC64 ? PPC::SUBFC8
  571. : PPC::SUBFC);
  572. const MCInstrDesc& SubtractImmCarryingInst = TII.get(isPPC64 ? PPC::SUBFIC8
  573. : PPC::SUBFIC);
  574. const MCInstrDesc &MoveFromCondRegInst = TII.get(isPPC64 ? PPC::MFCR8
  575. : PPC::MFCR);
  576. const MCInstrDesc &StoreWordInst = TII.get(isPPC64 ? PPC::STW8 : PPC::STW);
  577. const MCInstrDesc &HashST =
  578. TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHSTP8 : PPC::HASHST8)
  579. : (HasPrivileged ? PPC::HASHSTP : PPC::HASHST));
  580. // Regarding this assert: Even though LR is saved in the caller's frame (i.e.,
  581. // LROffset is positive), that slot is callee-owned. Because PPC32 SVR4 has no
  582. // Red Zone, an asynchronous event (a form of "callee") could claim a frame &
  583. // overwrite it, so PPC32 SVR4 must claim at least a minimal frame to save LR.
  584. assert((isPPC64 || !isSVR4ABI || !(!FrameSize && (MustSaveLR || HasFP))) &&
  585. "FrameSize must be >0 to save/restore the FP or LR for 32-bit SVR4.");
  586. // Using the same bool variable as below to suppress compiler warnings.
  587. bool SingleScratchReg = findScratchRegister(
  588. &MBB, false, twoUniqueScratchRegsRequired(&MBB), &ScratchReg, &TempReg);
  589. assert(SingleScratchReg &&
  590. "Required number of registers not available in this block");
  591. SingleScratchReg = ScratchReg == TempReg;
  592. int64_t LROffset = getReturnSaveOffset();
  593. int64_t FPOffset = 0;
  594. if (HasFP) {
  595. MachineFrameInfo &MFI = MF.getFrameInfo();
  596. int FPIndex = FI->getFramePointerSaveIndex();
  597. assert(FPIndex && "No Frame Pointer Save Slot!");
  598. FPOffset = MFI.getObjectOffset(FPIndex);
  599. }
  600. int64_t BPOffset = 0;
  601. if (HasBP) {
  602. MachineFrameInfo &MFI = MF.getFrameInfo();
  603. int BPIndex = FI->getBasePointerSaveIndex();
  604. assert(BPIndex && "No Base Pointer Save Slot!");
  605. BPOffset = MFI.getObjectOffset(BPIndex);
  606. }
  607. int64_t PBPOffset = 0;
  608. if (FI->usesPICBase()) {
  609. MachineFrameInfo &MFI = MF.getFrameInfo();
  610. int PBPIndex = FI->getPICBasePointerSaveIndex();
  611. assert(PBPIndex && "No PIC Base Pointer Save Slot!");
  612. PBPOffset = MFI.getObjectOffset(PBPIndex);
  613. }
  614. // Get stack alignments.
  615. Align MaxAlign = MFI.getMaxAlign();
  616. if (HasBP && MaxAlign > 1)
  617. assert(Log2(MaxAlign) < 16 && "Invalid alignment!");
  618. // Frames of 32KB & larger require special handling because they cannot be
  619. // indexed into with a simple STDU/STWU/STD/STW immediate offset operand.
  620. bool isLargeFrame = !isInt<16>(NegFrameSize);
  621. // Check if we can move the stack update instruction (stdu) down the prologue
  622. // past the callee saves. Hopefully this will avoid the situation where the
  623. // saves are waiting for the update on the store with update to complete.
  624. MachineBasicBlock::iterator StackUpdateLoc = MBBI;
  625. bool MovingStackUpdateDown = false;
  626. // Check if we can move the stack update.
  627. if (stackUpdateCanBeMoved(MF)) {
  628. const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
  629. for (CalleeSavedInfo CSI : Info) {
  630. // If the callee saved register is spilled to a register instead of the
  631. // stack then the spill no longer uses the stack pointer.
  632. // This can lead to two consequences:
  633. // 1) We no longer need to update the stack because the function does not
  634. // spill any callee saved registers to stack.
  635. // 2) We have a situation where we still have to update the stack pointer
  636. // even though some registers are spilled to other registers. In
  637. // this case the current code moves the stack update to an incorrect
  638. // position.
  639. // In either case we should abort moving the stack update operation.
  640. if (CSI.isSpilledToReg()) {
  641. StackUpdateLoc = MBBI;
  642. MovingStackUpdateDown = false;
  643. break;
  644. }
  645. int FrIdx = CSI.getFrameIdx();
  646. // If the frame index is not negative the callee saved info belongs to a
  647. // stack object that is not a fixed stack object. We ignore non-fixed
  648. // stack objects because we won't move the stack update pointer past them.
  649. if (FrIdx >= 0)
  650. continue;
  651. if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0) {
  652. StackUpdateLoc++;
  653. MovingStackUpdateDown = true;
  654. } else {
  655. // We need all of the Frame Indices to meet these conditions.
  656. // If they do not, abort the whole operation.
  657. StackUpdateLoc = MBBI;
  658. MovingStackUpdateDown = false;
  659. break;
  660. }
  661. }
  662. // If the operation was not aborted then update the object offset.
  663. if (MovingStackUpdateDown) {
  664. for (CalleeSavedInfo CSI : Info) {
  665. int FrIdx = CSI.getFrameIdx();
  666. if (FrIdx < 0)
  667. MFI.setObjectOffset(FrIdx, MFI.getObjectOffset(FrIdx) + NegFrameSize);
  668. }
  669. }
  670. }
  671. // Where in the prologue we move the CR fields depends on how many scratch
  672. // registers we have, and if we need to save the link register or not. This
  673. // lambda is to avoid duplicating the logic in 2 places.
  674. auto BuildMoveFromCR = [&]() {
  675. if (isELFv2ABI && MustSaveCRs.size() == 1) {
  676. // In the ELFv2 ABI, we are not required to save all CR fields.
  677. // If only one CR field is clobbered, it is more efficient to use
  678. // mfocrf to selectively save just that field, because mfocrf has short
  679. // latency compares to mfcr.
  680. assert(isPPC64 && "V2 ABI is 64-bit only.");
  681. MachineInstrBuilder MIB =
  682. BuildMI(MBB, MBBI, dl, TII.get(PPC::MFOCRF8), TempReg);
  683. MIB.addReg(MustSaveCRs[0], RegState::Kill);
  684. } else {
  685. MachineInstrBuilder MIB =
  686. BuildMI(MBB, MBBI, dl, MoveFromCondRegInst, TempReg);
  687. for (unsigned CRfield : MustSaveCRs)
  688. MIB.addReg(CRfield, RegState::ImplicitKill);
  689. }
  690. };
  691. // If we need to spill the CR and the LR but we don't have two separate
  692. // registers available, we must spill them one at a time
  693. if (MustSaveCR && SingleScratchReg && MustSaveLR) {
  694. BuildMoveFromCR();
  695. BuildMI(MBB, MBBI, dl, StoreWordInst)
  696. .addReg(TempReg, getKillRegState(true))
  697. .addImm(CRSaveOffset)
  698. .addReg(SPReg);
  699. }
  700. if (MustSaveLR)
  701. BuildMI(MBB, MBBI, dl, MFLRInst, ScratchReg);
  702. if (MustSaveCR && !(SingleScratchReg && MustSaveLR))
  703. BuildMoveFromCR();
  704. if (HasRedZone) {
  705. if (HasFP)
  706. BuildMI(MBB, MBBI, dl, StoreInst)
  707. .addReg(FPReg)
  708. .addImm(FPOffset)
  709. .addReg(SPReg);
  710. if (FI->usesPICBase())
  711. BuildMI(MBB, MBBI, dl, StoreInst)
  712. .addReg(PPC::R30)
  713. .addImm(PBPOffset)
  714. .addReg(SPReg);
  715. if (HasBP)
  716. BuildMI(MBB, MBBI, dl, StoreInst)
  717. .addReg(BPReg)
  718. .addImm(BPOffset)
  719. .addReg(SPReg);
  720. }
  721. // Generate the instruction to store the LR. In the case where ROP protection
  722. // is required the register holding the LR should not be killed as it will be
  723. // used by the hash store instruction.
  724. if (MustSaveLR) {
  725. BuildMI(MBB, StackUpdateLoc, dl, StoreInst)
  726. .addReg(ScratchReg, getKillRegState(!HasROPProtect))
  727. .addImm(LROffset)
  728. .addReg(SPReg);
  729. // Add the ROP protection Hash Store instruction.
  730. // NOTE: This is technically a violation of the ABI. The hash can be saved
  731. // up to 512 bytes into the Protected Zone. This can be outside of the
  732. // initial 288 byte volatile program storage region in the Protected Zone.
  733. // However, this restriction will be removed in an upcoming revision of the
  734. // ABI.
  735. if (HasROPProtect) {
  736. const int SaveIndex = FI->getROPProtectionHashSaveIndex();
  737. const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);
  738. assert((ImmOffset <= -8 && ImmOffset >= -512) &&
  739. "ROP hash save offset out of range.");
  740. assert(((ImmOffset & 0x7) == 0) &&
  741. "ROP hash save offset must be 8 byte aligned.");
  742. BuildMI(MBB, StackUpdateLoc, dl, HashST)
  743. .addReg(ScratchReg, getKillRegState(true))
  744. .addImm(ImmOffset)
  745. .addReg(SPReg);
  746. }
  747. }
  748. if (MustSaveCR &&
  749. !(SingleScratchReg && MustSaveLR)) {
  750. assert(HasRedZone && "A red zone is always available on PPC64");
  751. BuildMI(MBB, MBBI, dl, StoreWordInst)
  752. .addReg(TempReg, getKillRegState(true))
  753. .addImm(CRSaveOffset)
  754. .addReg(SPReg);
  755. }
  756. // Skip the rest if this is a leaf function & all spills fit in the Red Zone.
  757. if (!FrameSize)
  758. return;
  759. // Adjust stack pointer: r1 += NegFrameSize.
  760. // If there is a preferred stack alignment, align R1 now
  761. if (HasBP && HasRedZone) {
  762. // Save a copy of r1 as the base pointer.
  763. BuildMI(MBB, MBBI, dl, OrInst, BPReg)
  764. .addReg(SPReg)
  765. .addReg(SPReg);
  766. }
  767. // Have we generated a STUX instruction to claim stack frame? If so,
  768. // the negated frame size will be placed in ScratchReg.
  769. bool HasSTUX = false;
  770. // If FrameSize <= TLI.getStackProbeSize(MF), as POWER ABI requires backchain
  771. // pointer is always stored at SP, we will get a free probe due to an essential
  772. // STU(X) instruction.
  773. if (TLI.hasInlineStackProbe(MF) && FrameSize > TLI.getStackProbeSize(MF)) {
  774. // To be consistent with other targets, a pseudo instruction is emitted and
  775. // will be later expanded in `inlineStackProbe`.
  776. BuildMI(MBB, MBBI, dl,
  777. TII.get(isPPC64 ? PPC::PROBED_STACKALLOC_64
  778. : PPC::PROBED_STACKALLOC_32))
  779. .addDef(TempReg)
  780. .addDef(ScratchReg) // ScratchReg stores the old sp.
  781. .addImm(NegFrameSize);
  782. // FIXME: HasSTUX is only read if HasRedZone is not set, in such case, we
  783. // update the ScratchReg to meet the assumption that ScratchReg contains
  784. // the NegFrameSize. This solution is rather tricky.
  785. if (!HasRedZone) {
  786. BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
  787. .addReg(ScratchReg)
  788. .addReg(SPReg);
  789. HasSTUX = true;
  790. }
  791. } else {
  792. // This condition must be kept in sync with canUseAsPrologue.
  793. if (HasBP && MaxAlign > 1) {
  794. if (isPPC64)
  795. BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), ScratchReg)
  796. .addReg(SPReg)
  797. .addImm(0)
  798. .addImm(64 - Log2(MaxAlign));
  799. else // PPC32...
  800. BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), ScratchReg)
  801. .addReg(SPReg)
  802. .addImm(0)
  803. .addImm(32 - Log2(MaxAlign))
  804. .addImm(31);
  805. if (!isLargeFrame) {
  806. BuildMI(MBB, MBBI, dl, SubtractImmCarryingInst, ScratchReg)
  807. .addReg(ScratchReg, RegState::Kill)
  808. .addImm(NegFrameSize);
  809. } else {
  810. assert(!SingleScratchReg && "Only a single scratch reg available");
  811. BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, TempReg)
  812. .addImm(NegFrameSize >> 16);
  813. BuildMI(MBB, MBBI, dl, OrImmInst, TempReg)
  814. .addReg(TempReg, RegState::Kill)
  815. .addImm(NegFrameSize & 0xFFFF);
  816. BuildMI(MBB, MBBI, dl, SubtractCarryingInst, ScratchReg)
  817. .addReg(ScratchReg, RegState::Kill)
  818. .addReg(TempReg, RegState::Kill);
  819. }
  820. BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
  821. .addReg(SPReg, RegState::Kill)
  822. .addReg(SPReg)
  823. .addReg(ScratchReg);
  824. HasSTUX = true;
  825. } else if (!isLargeFrame) {
  826. BuildMI(MBB, StackUpdateLoc, dl, StoreUpdtInst, SPReg)
  827. .addReg(SPReg)
  828. .addImm(NegFrameSize)
  829. .addReg(SPReg);
  830. } else {
  831. BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
  832. .addImm(NegFrameSize >> 16);
  833. BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
  834. .addReg(ScratchReg, RegState::Kill)
  835. .addImm(NegFrameSize & 0xFFFF);
  836. BuildMI(MBB, MBBI, dl, StoreUpdtIdxInst, SPReg)
  837. .addReg(SPReg, RegState::Kill)
  838. .addReg(SPReg)
  839. .addReg(ScratchReg);
  840. HasSTUX = true;
  841. }
  842. }
  843. // Save the TOC register after the stack pointer update if a prologue TOC
  844. // save is required for the function.
  845. if (MustSaveTOC) {
  846. assert(isELFv2ABI && "TOC saves in the prologue only supported on ELFv2");
  847. BuildMI(MBB, StackUpdateLoc, dl, TII.get(PPC::STD))
  848. .addReg(TOCReg, getKillRegState(true))
  849. .addImm(TOCSaveOffset)
  850. .addReg(SPReg);
  851. }
  852. if (!HasRedZone) {
  853. assert(!isPPC64 && "A red zone is always available on PPC64");
  854. if (HasSTUX) {
  855. // The negated frame size is in ScratchReg, and the SPReg has been
  856. // decremented by the frame size: SPReg = old SPReg + ScratchReg.
  857. // Since FPOffset, PBPOffset, etc. are relative to the beginning of
  858. // the stack frame (i.e. the old SP), ideally, we would put the old
  859. // SP into a register and use it as the base for the stores. The
  860. // problem is that the only available register may be ScratchReg,
  861. // which could be R0, and R0 cannot be used as a base address.
  862. // First, set ScratchReg to the old SP. This may need to be modified
  863. // later.
  864. BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBF), ScratchReg)
  865. .addReg(ScratchReg, RegState::Kill)
  866. .addReg(SPReg);
  867. if (ScratchReg == PPC::R0) {
  868. // R0 cannot be used as a base register, but it can be used as an
  869. // index in a store-indexed.
  870. int LastOffset = 0;
  871. if (HasFP) {
  872. // R0 += (FPOffset-LastOffset).
  873. // Need addic, since addi treats R0 as 0.
  874. BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
  875. .addReg(ScratchReg)
  876. .addImm(FPOffset-LastOffset);
  877. LastOffset = FPOffset;
  878. // Store FP into *R0.
  879. BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
  880. .addReg(FPReg, RegState::Kill) // Save FP.
  881. .addReg(PPC::ZERO)
  882. .addReg(ScratchReg); // This will be the index (R0 is ok here).
  883. }
  884. if (FI->usesPICBase()) {
  885. // R0 += (PBPOffset-LastOffset).
  886. BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
  887. .addReg(ScratchReg)
  888. .addImm(PBPOffset-LastOffset);
  889. LastOffset = PBPOffset;
  890. BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
  891. .addReg(PPC::R30, RegState::Kill) // Save PIC base pointer.
  892. .addReg(PPC::ZERO)
  893. .addReg(ScratchReg); // This will be the index (R0 is ok here).
  894. }
  895. if (HasBP) {
  896. // R0 += (BPOffset-LastOffset).
  897. BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), ScratchReg)
  898. .addReg(ScratchReg)
  899. .addImm(BPOffset-LastOffset);
  900. LastOffset = BPOffset;
  901. BuildMI(MBB, MBBI, dl, TII.get(PPC::STWX))
  902. .addReg(BPReg, RegState::Kill) // Save BP.
  903. .addReg(PPC::ZERO)
  904. .addReg(ScratchReg); // This will be the index (R0 is ok here).
  905. // BP = R0-LastOffset
  906. BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDIC), BPReg)
  907. .addReg(ScratchReg, RegState::Kill)
  908. .addImm(-LastOffset);
  909. }
  910. } else {
  911. // ScratchReg is not R0, so use it as the base register. It is
  912. // already set to the old SP, so we can use the offsets directly.
  913. // Now that the stack frame has been allocated, save all the necessary
  914. // registers using ScratchReg as the base address.
  915. if (HasFP)
  916. BuildMI(MBB, MBBI, dl, StoreInst)
  917. .addReg(FPReg)
  918. .addImm(FPOffset)
  919. .addReg(ScratchReg);
  920. if (FI->usesPICBase())
  921. BuildMI(MBB, MBBI, dl, StoreInst)
  922. .addReg(PPC::R30)
  923. .addImm(PBPOffset)
  924. .addReg(ScratchReg);
  925. if (HasBP) {
  926. BuildMI(MBB, MBBI, dl, StoreInst)
  927. .addReg(BPReg)
  928. .addImm(BPOffset)
  929. .addReg(ScratchReg);
  930. BuildMI(MBB, MBBI, dl, OrInst, BPReg)
  931. .addReg(ScratchReg, RegState::Kill)
  932. .addReg(ScratchReg);
  933. }
  934. }
  935. } else {
  936. // The frame size is a known 16-bit constant (fitting in the immediate
  937. // field of STWU). To be here we have to be compiling for PPC32.
  938. // Since the SPReg has been decreased by FrameSize, add it back to each
  939. // offset.
  940. if (HasFP)
  941. BuildMI(MBB, MBBI, dl, StoreInst)
  942. .addReg(FPReg)
  943. .addImm(FrameSize + FPOffset)
  944. .addReg(SPReg);
  945. if (FI->usesPICBase())
  946. BuildMI(MBB, MBBI, dl, StoreInst)
  947. .addReg(PPC::R30)
  948. .addImm(FrameSize + PBPOffset)
  949. .addReg(SPReg);
  950. if (HasBP) {
  951. BuildMI(MBB, MBBI, dl, StoreInst)
  952. .addReg(BPReg)
  953. .addImm(FrameSize + BPOffset)
  954. .addReg(SPReg);
  955. BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), BPReg)
  956. .addReg(SPReg)
  957. .addImm(FrameSize);
  958. }
  959. }
  960. }
  961. // Add Call Frame Information for the instructions we generated above.
  962. if (needsCFI) {
  963. unsigned CFIIndex;
  964. if (HasBP) {
  965. // Define CFA in terms of BP. Do this in preference to using FP/SP,
  966. // because if the stack needed aligning then CFA won't be at a fixed
  967. // offset from FP/SP.
  968. unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
  969. CFIIndex = MF.addFrameInst(
  970. MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
  971. } else {
  972. // Adjust the definition of CFA to account for the change in SP.
  973. assert(NegFrameSize);
  974. CFIIndex = MF.addFrameInst(
  975. MCCFIInstruction::cfiDefCfaOffset(nullptr, -NegFrameSize));
  976. }
  977. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  978. .addCFIIndex(CFIIndex);
  979. if (HasFP) {
  980. // Describe where FP was saved, at a fixed offset from CFA.
  981. unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
  982. CFIIndex = MF.addFrameInst(
  983. MCCFIInstruction::createOffset(nullptr, Reg, FPOffset));
  984. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  985. .addCFIIndex(CFIIndex);
  986. }
  987. if (FI->usesPICBase()) {
  988. // Describe where FP was saved, at a fixed offset from CFA.
  989. unsigned Reg = MRI->getDwarfRegNum(PPC::R30, true);
  990. CFIIndex = MF.addFrameInst(
  991. MCCFIInstruction::createOffset(nullptr, Reg, PBPOffset));
  992. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  993. .addCFIIndex(CFIIndex);
  994. }
  995. if (HasBP) {
  996. // Describe where BP was saved, at a fixed offset from CFA.
  997. unsigned Reg = MRI->getDwarfRegNum(BPReg, true);
  998. CFIIndex = MF.addFrameInst(
  999. MCCFIInstruction::createOffset(nullptr, Reg, BPOffset));
  1000. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1001. .addCFIIndex(CFIIndex);
  1002. }
  1003. if (MustSaveLR) {
  1004. // Describe where LR was saved, at a fixed offset from CFA.
  1005. unsigned Reg = MRI->getDwarfRegNum(LRReg, true);
  1006. CFIIndex = MF.addFrameInst(
  1007. MCCFIInstruction::createOffset(nullptr, Reg, LROffset));
  1008. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1009. .addCFIIndex(CFIIndex);
  1010. }
  1011. }
  1012. // If there is a frame pointer, copy R1 into R31
  1013. if (HasFP) {
  1014. BuildMI(MBB, MBBI, dl, OrInst, FPReg)
  1015. .addReg(SPReg)
  1016. .addReg(SPReg);
  1017. if (!HasBP && needsCFI) {
  1018. // Change the definition of CFA from SP+offset to FP+offset, because SP
  1019. // will change at every alloca.
  1020. unsigned Reg = MRI->getDwarfRegNum(FPReg, true);
  1021. unsigned CFIIndex = MF.addFrameInst(
  1022. MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
  1023. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1024. .addCFIIndex(CFIIndex);
  1025. }
  1026. }
  1027. if (needsCFI) {
  1028. // Describe where callee saved registers were saved, at fixed offsets from
  1029. // CFA.
  1030. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  1031. for (const CalleeSavedInfo &I : CSI) {
  1032. Register Reg = I.getReg();
  1033. if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
  1034. // This is a bit of a hack: CR2LT, CR2GT, CR2EQ and CR2UN are just
  1035. // subregisters of CR2. We just need to emit a move of CR2.
  1036. if (PPC::CRBITRCRegClass.contains(Reg))
  1037. continue;
  1038. if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
  1039. continue;
  1040. // For SVR4, don't emit a move for the CR spill slot if we haven't
  1041. // spilled CRs.
  1042. if (isSVR4ABI && (PPC::CR2 <= Reg && Reg <= PPC::CR4)
  1043. && !MustSaveCR)
  1044. continue;
  1045. // For 64-bit SVR4 when we have spilled CRs, the spill location
  1046. // is SP+8, not a frame-relative slot.
  1047. if (isSVR4ABI && isPPC64 && (PPC::CR2 <= Reg && Reg <= PPC::CR4)) {
  1048. // In the ELFv1 ABI, only CR2 is noted in CFI and stands in for
  1049. // the whole CR word. In the ELFv2 ABI, every CR that was
  1050. // actually saved gets its own CFI record.
  1051. Register CRReg = isELFv2ABI? Reg : PPC::CR2;
  1052. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  1053. nullptr, MRI->getDwarfRegNum(CRReg, true), CRSaveOffset));
  1054. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1055. .addCFIIndex(CFIIndex);
  1056. continue;
  1057. }
  1058. if (I.isSpilledToReg()) {
  1059. unsigned SpilledReg = I.getDstReg();
  1060. unsigned CFIRegister = MF.addFrameInst(MCCFIInstruction::createRegister(
  1061. nullptr, MRI->getDwarfRegNum(Reg, true),
  1062. MRI->getDwarfRegNum(SpilledReg, true)));
  1063. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1064. .addCFIIndex(CFIRegister);
  1065. } else {
  1066. int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
  1067. // We have changed the object offset above but we do not want to change
  1068. // the actual offsets in the CFI instruction so we have to undo the
  1069. // offset change here.
  1070. if (MovingStackUpdateDown)
  1071. Offset -= NegFrameSize;
  1072. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  1073. nullptr, MRI->getDwarfRegNum(Reg, true), Offset));
  1074. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1075. .addCFIIndex(CFIIndex);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. void PPCFrameLowering::inlineStackProbe(MachineFunction &MF,
  1081. MachineBasicBlock &PrologMBB) const {
  1082. bool isPPC64 = Subtarget.isPPC64();
  1083. const PPCTargetLowering &TLI = *Subtarget.getTargetLowering();
  1084. const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
  1085. MachineFrameInfo &MFI = MF.getFrameInfo();
  1086. MachineModuleInfo &MMI = MF.getMMI();
  1087. const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
  1088. // AIX assembler does not support cfi directives.
  1089. const bool needsCFI = MF.needsFrameMoves() && !Subtarget.isAIXABI();
  1090. auto StackAllocMIPos = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
  1091. int Opc = MI.getOpcode();
  1092. return Opc == PPC::PROBED_STACKALLOC_64 || Opc == PPC::PROBED_STACKALLOC_32;
  1093. });
  1094. if (StackAllocMIPos == PrologMBB.end())
  1095. return;
  1096. const BasicBlock *ProbedBB = PrologMBB.getBasicBlock();
  1097. MachineBasicBlock *CurrentMBB = &PrologMBB;
  1098. DebugLoc DL = PrologMBB.findDebugLoc(StackAllocMIPos);
  1099. MachineInstr &MI = *StackAllocMIPos;
  1100. int64_t NegFrameSize = MI.getOperand(2).getImm();
  1101. unsigned ProbeSize = TLI.getStackProbeSize(MF);
  1102. int64_t NegProbeSize = -(int64_t)ProbeSize;
  1103. assert(isInt<32>(NegProbeSize) && "Unhandled probe size");
  1104. int64_t NumBlocks = NegFrameSize / NegProbeSize;
  1105. int64_t NegResidualSize = NegFrameSize % NegProbeSize;
  1106. Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
  1107. Register ScratchReg = MI.getOperand(0).getReg();
  1108. Register FPReg = MI.getOperand(1).getReg();
  1109. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  1110. bool HasBP = RegInfo->hasBasePointer(MF);
  1111. Register BPReg = RegInfo->getBaseRegister(MF);
  1112. Align MaxAlign = MFI.getMaxAlign();
  1113. bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
  1114. const MCInstrDesc &CopyInst = TII.get(isPPC64 ? PPC::OR8 : PPC::OR);
  1115. // Subroutines to generate .cfi_* directives.
  1116. auto buildDefCFAReg = [&](MachineBasicBlock &MBB,
  1117. MachineBasicBlock::iterator MBBI, Register Reg) {
  1118. unsigned RegNum = MRI->getDwarfRegNum(Reg, true);
  1119. unsigned CFIIndex = MF.addFrameInst(
  1120. MCCFIInstruction::createDefCfaRegister(nullptr, RegNum));
  1121. BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1122. .addCFIIndex(CFIIndex);
  1123. };
  1124. auto buildDefCFA = [&](MachineBasicBlock &MBB,
  1125. MachineBasicBlock::iterator MBBI, Register Reg,
  1126. int Offset) {
  1127. unsigned RegNum = MRI->getDwarfRegNum(Reg, true);
  1128. unsigned CFIIndex = MBB.getParent()->addFrameInst(
  1129. MCCFIInstruction::cfiDefCfa(nullptr, RegNum, Offset));
  1130. BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1131. .addCFIIndex(CFIIndex);
  1132. };
  1133. // Subroutine to determine if we can use the Imm as part of d-form.
  1134. auto CanUseDForm = [](int64_t Imm) { return isInt<16>(Imm) && Imm % 4 == 0; };
  1135. // Subroutine to materialize the Imm into TempReg.
  1136. auto MaterializeImm = [&](MachineBasicBlock &MBB,
  1137. MachineBasicBlock::iterator MBBI, int64_t Imm,
  1138. Register &TempReg) {
  1139. assert(isInt<32>(Imm) && "Unhandled imm");
  1140. if (isInt<16>(Imm))
  1141. BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LI8 : PPC::LI), TempReg)
  1142. .addImm(Imm);
  1143. else {
  1144. BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
  1145. .addImm(Imm >> 16);
  1146. BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::ORI8 : PPC::ORI), TempReg)
  1147. .addReg(TempReg)
  1148. .addImm(Imm & 0xFFFF);
  1149. }
  1150. };
  1151. // Subroutine to store frame pointer and decrease stack pointer by probe size.
  1152. auto allocateAndProbe = [&](MachineBasicBlock &MBB,
  1153. MachineBasicBlock::iterator MBBI, int64_t NegSize,
  1154. Register NegSizeReg, bool UseDForm,
  1155. Register StoreReg) {
  1156. if (UseDForm)
  1157. BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDU : PPC::STWU), SPReg)
  1158. .addReg(StoreReg)
  1159. .addImm(NegSize)
  1160. .addReg(SPReg);
  1161. else
  1162. BuildMI(MBB, MBBI, DL, TII.get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
  1163. .addReg(StoreReg)
  1164. .addReg(SPReg)
  1165. .addReg(NegSizeReg);
  1166. };
  1167. // Used to probe stack when realignment is required.
  1168. // Note that, according to ABI's requirement, *sp must always equals the
  1169. // value of back-chain pointer, only st(w|d)u(x) can be used to update sp.
  1170. // Following is pseudo code:
  1171. // final_sp = (sp & align) + negframesize;
  1172. // neg_gap = final_sp - sp;
  1173. // while (neg_gap < negprobesize) {
  1174. // stdu fp, negprobesize(sp);
  1175. // neg_gap -= negprobesize;
  1176. // }
  1177. // stdux fp, sp, neg_gap
  1178. //
  1179. // When HasBP & HasRedzone, back-chain pointer is already saved in BPReg
  1180. // before probe code, we don't need to save it, so we get one additional reg
  1181. // that can be used to materialize the probeside if needed to use xform.
  1182. // Otherwise, we can NOT materialize probeside, so we can only use Dform for
  1183. // now.
  1184. //
  1185. // The allocations are:
  1186. // if (HasBP && HasRedzone) {
  1187. // r0: materialize the probesize if needed so that we can use xform.
  1188. // r12: `neg_gap`
  1189. // } else {
  1190. // r0: back-chain pointer
  1191. // r12: `neg_gap`.
  1192. // }
  1193. auto probeRealignedStack = [&](MachineBasicBlock &MBB,
  1194. MachineBasicBlock::iterator MBBI,
  1195. Register ScratchReg, Register TempReg) {
  1196. assert(HasBP && "The function is supposed to have base pointer when its "
  1197. "stack is realigned.");
  1198. assert(isPowerOf2_64(ProbeSize) && "Probe size should be power of 2");
  1199. // FIXME: We can eliminate this limitation if we get more infomation about
  1200. // which part of redzone are already used. Used redzone can be treated
  1201. // probed. But there might be `holes' in redzone probed, this could
  1202. // complicate the implementation.
  1203. assert(ProbeSize >= Subtarget.getRedZoneSize() &&
  1204. "Probe size should be larger or equal to the size of red-zone so "
  1205. "that red-zone is not clobbered by probing.");
  1206. Register &FinalStackPtr = TempReg;
  1207. // FIXME: We only support NegProbeSize materializable by DForm currently.
  1208. // When HasBP && HasRedzone, we can use xform if we have an additional idle
  1209. // register.
  1210. NegProbeSize = std::max(NegProbeSize, -((int64_t)1 << 15));
  1211. assert(isInt<16>(NegProbeSize) &&
  1212. "NegProbeSize should be materializable by DForm");
  1213. Register CRReg = PPC::CR0;
  1214. // Layout of output assembly kinda like:
  1215. // bb.0:
  1216. // ...
  1217. // sub $scratchreg, $finalsp, r1
  1218. // cmpdi $scratchreg, <negprobesize>
  1219. // bge bb.2
  1220. // bb.1:
  1221. // stdu <backchain>, <negprobesize>(r1)
  1222. // sub $scratchreg, $scratchreg, negprobesize
  1223. // cmpdi $scratchreg, <negprobesize>
  1224. // blt bb.1
  1225. // bb.2:
  1226. // stdux <backchain>, r1, $scratchreg
  1227. MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
  1228. MachineBasicBlock *ProbeLoopBodyMBB = MF.CreateMachineBasicBlock(ProbedBB);
  1229. MF.insert(MBBInsertPoint, ProbeLoopBodyMBB);
  1230. MachineBasicBlock *ProbeExitMBB = MF.CreateMachineBasicBlock(ProbedBB);
  1231. MF.insert(MBBInsertPoint, ProbeExitMBB);
  1232. // bb.2
  1233. {
  1234. Register BackChainPointer = HasRedZone ? BPReg : TempReg;
  1235. allocateAndProbe(*ProbeExitMBB, ProbeExitMBB->end(), 0, ScratchReg, false,
  1236. BackChainPointer);
  1237. if (HasRedZone)
  1238. // PROBED_STACKALLOC_64 assumes Operand(1) stores the old sp, copy BPReg
  1239. // to TempReg to satisfy it.
  1240. BuildMI(*ProbeExitMBB, ProbeExitMBB->end(), DL, CopyInst, TempReg)
  1241. .addReg(BPReg)
  1242. .addReg(BPReg);
  1243. ProbeExitMBB->splice(ProbeExitMBB->end(), &MBB, MBBI, MBB.end());
  1244. ProbeExitMBB->transferSuccessorsAndUpdatePHIs(&MBB);
  1245. }
  1246. // bb.0
  1247. {
  1248. BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), ScratchReg)
  1249. .addReg(SPReg)
  1250. .addReg(FinalStackPtr);
  1251. if (!HasRedZone)
  1252. BuildMI(&MBB, DL, CopyInst, TempReg).addReg(SPReg).addReg(SPReg);
  1253. BuildMI(&MBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI), CRReg)
  1254. .addReg(ScratchReg)
  1255. .addImm(NegProbeSize);
  1256. BuildMI(&MBB, DL, TII.get(PPC::BCC))
  1257. .addImm(PPC::PRED_GE)
  1258. .addReg(CRReg)
  1259. .addMBB(ProbeExitMBB);
  1260. MBB.addSuccessor(ProbeLoopBodyMBB);
  1261. MBB.addSuccessor(ProbeExitMBB);
  1262. }
  1263. // bb.1
  1264. {
  1265. Register BackChainPointer = HasRedZone ? BPReg : TempReg;
  1266. allocateAndProbe(*ProbeLoopBodyMBB, ProbeLoopBodyMBB->end(), NegProbeSize,
  1267. 0, true /*UseDForm*/, BackChainPointer);
  1268. BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::ADDI8 : PPC::ADDI),
  1269. ScratchReg)
  1270. .addReg(ScratchReg)
  1271. .addImm(-NegProbeSize);
  1272. BuildMI(ProbeLoopBodyMBB, DL, TII.get(isPPC64 ? PPC::CMPDI : PPC::CMPWI),
  1273. CRReg)
  1274. .addReg(ScratchReg)
  1275. .addImm(NegProbeSize);
  1276. BuildMI(ProbeLoopBodyMBB, DL, TII.get(PPC::BCC))
  1277. .addImm(PPC::PRED_LT)
  1278. .addReg(CRReg)
  1279. .addMBB(ProbeLoopBodyMBB);
  1280. ProbeLoopBodyMBB->addSuccessor(ProbeExitMBB);
  1281. ProbeLoopBodyMBB->addSuccessor(ProbeLoopBodyMBB);
  1282. }
  1283. // Update liveins.
  1284. recomputeLiveIns(*ProbeLoopBodyMBB);
  1285. recomputeLiveIns(*ProbeExitMBB);
  1286. return ProbeExitMBB;
  1287. };
  1288. // For case HasBP && MaxAlign > 1, we have to realign the SP by performing
  1289. // SP = SP - SP % MaxAlign, thus make the probe more like dynamic probe since
  1290. // the offset subtracted from SP is determined by SP's runtime value.
  1291. if (HasBP && MaxAlign > 1) {
  1292. // Calculate final stack pointer.
  1293. if (isPPC64)
  1294. BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLDICL), ScratchReg)
  1295. .addReg(SPReg)
  1296. .addImm(0)
  1297. .addImm(64 - Log2(MaxAlign));
  1298. else
  1299. BuildMI(*CurrentMBB, {MI}, DL, TII.get(PPC::RLWINM), ScratchReg)
  1300. .addReg(SPReg)
  1301. .addImm(0)
  1302. .addImm(32 - Log2(MaxAlign))
  1303. .addImm(31);
  1304. BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::SUBF8 : PPC::SUBF),
  1305. FPReg)
  1306. .addReg(ScratchReg)
  1307. .addReg(SPReg);
  1308. MaterializeImm(*CurrentMBB, {MI}, NegFrameSize, ScratchReg);
  1309. BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
  1310. FPReg)
  1311. .addReg(ScratchReg)
  1312. .addReg(FPReg);
  1313. CurrentMBB = probeRealignedStack(*CurrentMBB, {MI}, ScratchReg, FPReg);
  1314. if (needsCFI)
  1315. buildDefCFAReg(*CurrentMBB, {MI}, FPReg);
  1316. } else {
  1317. // Initialize current frame pointer.
  1318. BuildMI(*CurrentMBB, {MI}, DL, CopyInst, FPReg).addReg(SPReg).addReg(SPReg);
  1319. // Use FPReg to calculate CFA.
  1320. if (needsCFI)
  1321. buildDefCFA(*CurrentMBB, {MI}, FPReg, 0);
  1322. // Probe residual part.
  1323. if (NegResidualSize) {
  1324. bool ResidualUseDForm = CanUseDForm(NegResidualSize);
  1325. if (!ResidualUseDForm)
  1326. MaterializeImm(*CurrentMBB, {MI}, NegResidualSize, ScratchReg);
  1327. allocateAndProbe(*CurrentMBB, {MI}, NegResidualSize, ScratchReg,
  1328. ResidualUseDForm, FPReg);
  1329. }
  1330. bool UseDForm = CanUseDForm(NegProbeSize);
  1331. // If number of blocks is small, just probe them directly.
  1332. if (NumBlocks < 3) {
  1333. if (!UseDForm)
  1334. MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);
  1335. for (int i = 0; i < NumBlocks; ++i)
  1336. allocateAndProbe(*CurrentMBB, {MI}, NegProbeSize, ScratchReg, UseDForm,
  1337. FPReg);
  1338. if (needsCFI) {
  1339. // Restore using SPReg to calculate CFA.
  1340. buildDefCFAReg(*CurrentMBB, {MI}, SPReg);
  1341. }
  1342. } else {
  1343. // Since CTR is a volatile register and current shrinkwrap implementation
  1344. // won't choose an MBB in a loop as the PrologMBB, it's safe to synthesize a
  1345. // CTR loop to probe.
  1346. // Calculate trip count and stores it in CTRReg.
  1347. MaterializeImm(*CurrentMBB, {MI}, NumBlocks, ScratchReg);
  1348. BuildMI(*CurrentMBB, {MI}, DL, TII.get(isPPC64 ? PPC::MTCTR8 : PPC::MTCTR))
  1349. .addReg(ScratchReg, RegState::Kill);
  1350. if (!UseDForm)
  1351. MaterializeImm(*CurrentMBB, {MI}, NegProbeSize, ScratchReg);
  1352. // Create MBBs of the loop.
  1353. MachineFunction::iterator MBBInsertPoint =
  1354. std::next(CurrentMBB->getIterator());
  1355. MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(ProbedBB);
  1356. MF.insert(MBBInsertPoint, LoopMBB);
  1357. MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(ProbedBB);
  1358. MF.insert(MBBInsertPoint, ExitMBB);
  1359. // Synthesize the loop body.
  1360. allocateAndProbe(*LoopMBB, LoopMBB->end(), NegProbeSize, ScratchReg,
  1361. UseDForm, FPReg);
  1362. BuildMI(LoopMBB, DL, TII.get(isPPC64 ? PPC::BDNZ8 : PPC::BDNZ))
  1363. .addMBB(LoopMBB);
  1364. LoopMBB->addSuccessor(ExitMBB);
  1365. LoopMBB->addSuccessor(LoopMBB);
  1366. // Synthesize the exit MBB.
  1367. ExitMBB->splice(ExitMBB->end(), CurrentMBB,
  1368. std::next(MachineBasicBlock::iterator(MI)),
  1369. CurrentMBB->end());
  1370. ExitMBB->transferSuccessorsAndUpdatePHIs(CurrentMBB);
  1371. CurrentMBB->addSuccessor(LoopMBB);
  1372. if (needsCFI) {
  1373. // Restore using SPReg to calculate CFA.
  1374. buildDefCFAReg(*ExitMBB, ExitMBB->begin(), SPReg);
  1375. }
  1376. // Update liveins.
  1377. recomputeLiveIns(*LoopMBB);
  1378. recomputeLiveIns(*ExitMBB);
  1379. }
  1380. }
  1381. ++NumPrologProbed;
  1382. MI.eraseFromParent();
  1383. }
  1384. void PPCFrameLowering::emitEpilogue(MachineFunction &MF,
  1385. MachineBasicBlock &MBB) const {
  1386. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  1387. DebugLoc dl;
  1388. if (MBBI != MBB.end())
  1389. dl = MBBI->getDebugLoc();
  1390. const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
  1391. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  1392. // Get alignment info so we know how to restore the SP.
  1393. const MachineFrameInfo &MFI = MF.getFrameInfo();
  1394. // Get the number of bytes allocated from the FrameInfo.
  1395. int64_t FrameSize = MFI.getStackSize();
  1396. // Get processor type.
  1397. bool isPPC64 = Subtarget.isPPC64();
  1398. // Check if the link register (LR) has been saved.
  1399. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  1400. bool MustSaveLR = FI->mustSaveLR();
  1401. const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
  1402. bool MustSaveCR = !MustSaveCRs.empty();
  1403. // Do we have a frame pointer and/or base pointer for this function?
  1404. bool HasFP = hasFP(MF);
  1405. bool HasBP = RegInfo->hasBasePointer(MF);
  1406. bool HasRedZone = Subtarget.isPPC64() || !Subtarget.isSVR4ABI();
  1407. bool HasROPProtect = Subtarget.hasROPProtect();
  1408. bool HasPrivileged = Subtarget.hasPrivileged();
  1409. Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
  1410. Register BPReg = RegInfo->getBaseRegister(MF);
  1411. Register FPReg = isPPC64 ? PPC::X31 : PPC::R31;
  1412. Register ScratchReg;
  1413. Register TempReg = isPPC64 ? PPC::X12 : PPC::R12; // another scratch reg
  1414. const MCInstrDesc& MTLRInst = TII.get( isPPC64 ? PPC::MTLR8
  1415. : PPC::MTLR );
  1416. const MCInstrDesc& LoadInst = TII.get( isPPC64 ? PPC::LD
  1417. : PPC::LWZ );
  1418. const MCInstrDesc& LoadImmShiftedInst = TII.get( isPPC64 ? PPC::LIS8
  1419. : PPC::LIS );
  1420. const MCInstrDesc& OrInst = TII.get(isPPC64 ? PPC::OR8
  1421. : PPC::OR );
  1422. const MCInstrDesc& OrImmInst = TII.get( isPPC64 ? PPC::ORI8
  1423. : PPC::ORI );
  1424. const MCInstrDesc& AddImmInst = TII.get( isPPC64 ? PPC::ADDI8
  1425. : PPC::ADDI );
  1426. const MCInstrDesc& AddInst = TII.get( isPPC64 ? PPC::ADD8
  1427. : PPC::ADD4 );
  1428. const MCInstrDesc& LoadWordInst = TII.get( isPPC64 ? PPC::LWZ8
  1429. : PPC::LWZ);
  1430. const MCInstrDesc& MoveToCRInst = TII.get( isPPC64 ? PPC::MTOCRF8
  1431. : PPC::MTOCRF);
  1432. const MCInstrDesc &HashChk =
  1433. TII.get(isPPC64 ? (HasPrivileged ? PPC::HASHCHKP8 : PPC::HASHCHK8)
  1434. : (HasPrivileged ? PPC::HASHCHKP : PPC::HASHCHK));
  1435. int64_t LROffset = getReturnSaveOffset();
  1436. int64_t FPOffset = 0;
  1437. // Using the same bool variable as below to suppress compiler warnings.
  1438. bool SingleScratchReg = findScratchRegister(&MBB, true, false, &ScratchReg,
  1439. &TempReg);
  1440. assert(SingleScratchReg &&
  1441. "Could not find an available scratch register");
  1442. SingleScratchReg = ScratchReg == TempReg;
  1443. if (HasFP) {
  1444. int FPIndex = FI->getFramePointerSaveIndex();
  1445. assert(FPIndex && "No Frame Pointer Save Slot!");
  1446. FPOffset = MFI.getObjectOffset(FPIndex);
  1447. }
  1448. int64_t BPOffset = 0;
  1449. if (HasBP) {
  1450. int BPIndex = FI->getBasePointerSaveIndex();
  1451. assert(BPIndex && "No Base Pointer Save Slot!");
  1452. BPOffset = MFI.getObjectOffset(BPIndex);
  1453. }
  1454. int64_t PBPOffset = 0;
  1455. if (FI->usesPICBase()) {
  1456. int PBPIndex = FI->getPICBasePointerSaveIndex();
  1457. assert(PBPIndex && "No PIC Base Pointer Save Slot!");
  1458. PBPOffset = MFI.getObjectOffset(PBPIndex);
  1459. }
  1460. bool IsReturnBlock = (MBBI != MBB.end() && MBBI->isReturn());
  1461. if (IsReturnBlock) {
  1462. unsigned RetOpcode = MBBI->getOpcode();
  1463. bool UsesTCRet = RetOpcode == PPC::TCRETURNri ||
  1464. RetOpcode == PPC::TCRETURNdi ||
  1465. RetOpcode == PPC::TCRETURNai ||
  1466. RetOpcode == PPC::TCRETURNri8 ||
  1467. RetOpcode == PPC::TCRETURNdi8 ||
  1468. RetOpcode == PPC::TCRETURNai8;
  1469. if (UsesTCRet) {
  1470. int MaxTCRetDelta = FI->getTailCallSPDelta();
  1471. MachineOperand &StackAdjust = MBBI->getOperand(1);
  1472. assert(StackAdjust.isImm() && "Expecting immediate value.");
  1473. // Adjust stack pointer.
  1474. int StackAdj = StackAdjust.getImm();
  1475. int Delta = StackAdj - MaxTCRetDelta;
  1476. assert((Delta >= 0) && "Delta must be positive");
  1477. if (MaxTCRetDelta>0)
  1478. FrameSize += (StackAdj +Delta);
  1479. else
  1480. FrameSize += StackAdj;
  1481. }
  1482. }
  1483. // Frames of 32KB & larger require special handling because they cannot be
  1484. // indexed into with a simple LD/LWZ immediate offset operand.
  1485. bool isLargeFrame = !isInt<16>(FrameSize);
  1486. // On targets without red zone, the SP needs to be restored last, so that
  1487. // all live contents of the stack frame are upwards of the SP. This means
  1488. // that we cannot restore SP just now, since there may be more registers
  1489. // to restore from the stack frame (e.g. R31). If the frame size is not
  1490. // a simple immediate value, we will need a spare register to hold the
  1491. // restored SP. If the frame size is known and small, we can simply adjust
  1492. // the offsets of the registers to be restored, and still use SP to restore
  1493. // them. In such case, the final update of SP will be to add the frame
  1494. // size to it.
  1495. // To simplify the code, set RBReg to the base register used to restore
  1496. // values from the stack, and set SPAdd to the value that needs to be added
  1497. // to the SP at the end. The default values are as if red zone was present.
  1498. unsigned RBReg = SPReg;
  1499. unsigned SPAdd = 0;
  1500. // Check if we can move the stack update instruction up the epilogue
  1501. // past the callee saves. This will allow the move to LR instruction
  1502. // to be executed before the restores of the callee saves which means
  1503. // that the callee saves can hide the latency from the MTLR instrcution.
  1504. MachineBasicBlock::iterator StackUpdateLoc = MBBI;
  1505. if (stackUpdateCanBeMoved(MF)) {
  1506. const std::vector<CalleeSavedInfo> & Info = MFI.getCalleeSavedInfo();
  1507. for (CalleeSavedInfo CSI : Info) {
  1508. // If the callee saved register is spilled to another register abort the
  1509. // stack update movement.
  1510. if (CSI.isSpilledToReg()) {
  1511. StackUpdateLoc = MBBI;
  1512. break;
  1513. }
  1514. int FrIdx = CSI.getFrameIdx();
  1515. // If the frame index is not negative the callee saved info belongs to a
  1516. // stack object that is not a fixed stack object. We ignore non-fixed
  1517. // stack objects because we won't move the update of the stack pointer
  1518. // past them.
  1519. if (FrIdx >= 0)
  1520. continue;
  1521. if (MFI.isFixedObjectIndex(FrIdx) && MFI.getObjectOffset(FrIdx) < 0)
  1522. StackUpdateLoc--;
  1523. else {
  1524. // Abort the operation as we can't update all CSR restores.
  1525. StackUpdateLoc = MBBI;
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. if (FrameSize) {
  1531. // In the prologue, the loaded (or persistent) stack pointer value is
  1532. // offset by the STDU/STDUX/STWU/STWUX instruction. For targets with red
  1533. // zone add this offset back now.
  1534. // If the function has a base pointer, the stack pointer has been copied
  1535. // to it so we can restore it by copying in the other direction.
  1536. if (HasRedZone && HasBP) {
  1537. BuildMI(MBB, MBBI, dl, OrInst, RBReg).
  1538. addReg(BPReg).
  1539. addReg(BPReg);
  1540. }
  1541. // If this function contained a fastcc call and GuaranteedTailCallOpt is
  1542. // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
  1543. // call which invalidates the stack pointer value in SP(0). So we use the
  1544. // value of R31 in this case. Similar situation exists with setjmp.
  1545. else if (FI->hasFastCall() || MF.exposesReturnsTwice()) {
  1546. assert(HasFP && "Expecting a valid frame pointer.");
  1547. if (!HasRedZone)
  1548. RBReg = FPReg;
  1549. if (!isLargeFrame) {
  1550. BuildMI(MBB, MBBI, dl, AddImmInst, RBReg)
  1551. .addReg(FPReg).addImm(FrameSize);
  1552. } else {
  1553. BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
  1554. .addImm(FrameSize >> 16);
  1555. BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
  1556. .addReg(ScratchReg, RegState::Kill)
  1557. .addImm(FrameSize & 0xFFFF);
  1558. BuildMI(MBB, MBBI, dl, AddInst)
  1559. .addReg(RBReg)
  1560. .addReg(FPReg)
  1561. .addReg(ScratchReg);
  1562. }
  1563. } else if (!isLargeFrame && !HasBP && !MFI.hasVarSizedObjects()) {
  1564. if (HasRedZone) {
  1565. BuildMI(MBB, StackUpdateLoc, dl, AddImmInst, SPReg)
  1566. .addReg(SPReg)
  1567. .addImm(FrameSize);
  1568. } else {
  1569. // Make sure that adding FrameSize will not overflow the max offset
  1570. // size.
  1571. assert(FPOffset <= 0 && BPOffset <= 0 && PBPOffset <= 0 &&
  1572. "Local offsets should be negative");
  1573. SPAdd = FrameSize;
  1574. FPOffset += FrameSize;
  1575. BPOffset += FrameSize;
  1576. PBPOffset += FrameSize;
  1577. }
  1578. } else {
  1579. // We don't want to use ScratchReg as a base register, because it
  1580. // could happen to be R0. Use FP instead, but make sure to preserve it.
  1581. if (!HasRedZone) {
  1582. // If FP is not saved, copy it to ScratchReg.
  1583. if (!HasFP)
  1584. BuildMI(MBB, MBBI, dl, OrInst, ScratchReg)
  1585. .addReg(FPReg)
  1586. .addReg(FPReg);
  1587. RBReg = FPReg;
  1588. }
  1589. BuildMI(MBB, StackUpdateLoc, dl, LoadInst, RBReg)
  1590. .addImm(0)
  1591. .addReg(SPReg);
  1592. }
  1593. }
  1594. assert(RBReg != ScratchReg && "Should have avoided ScratchReg");
  1595. // If there is no red zone, ScratchReg may be needed for holding a useful
  1596. // value (although not the base register). Make sure it is not overwritten
  1597. // too early.
  1598. // If we need to restore both the LR and the CR and we only have one
  1599. // available scratch register, we must do them one at a time.
  1600. if (MustSaveCR && SingleScratchReg && MustSaveLR) {
  1601. // Here TempReg == ScratchReg, and in the absence of red zone ScratchReg
  1602. // is live here.
  1603. assert(HasRedZone && "Expecting red zone");
  1604. BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)
  1605. .addImm(CRSaveOffset)
  1606. .addReg(SPReg);
  1607. for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
  1608. BuildMI(MBB, MBBI, dl, MoveToCRInst, MustSaveCRs[i])
  1609. .addReg(TempReg, getKillRegState(i == e-1));
  1610. }
  1611. // Delay restoring of the LR if ScratchReg is needed. This is ok, since
  1612. // LR is stored in the caller's stack frame. ScratchReg will be needed
  1613. // if RBReg is anything other than SP. We shouldn't use ScratchReg as
  1614. // a base register anyway, because it may happen to be R0.
  1615. bool LoadedLR = false;
  1616. if (MustSaveLR && RBReg == SPReg && isInt<16>(LROffset+SPAdd)) {
  1617. BuildMI(MBB, StackUpdateLoc, dl, LoadInst, ScratchReg)
  1618. .addImm(LROffset+SPAdd)
  1619. .addReg(RBReg);
  1620. LoadedLR = true;
  1621. }
  1622. if (MustSaveCR && !(SingleScratchReg && MustSaveLR)) {
  1623. assert(RBReg == SPReg && "Should be using SP as a base register");
  1624. BuildMI(MBB, MBBI, dl, LoadWordInst, TempReg)
  1625. .addImm(CRSaveOffset)
  1626. .addReg(RBReg);
  1627. }
  1628. if (HasFP) {
  1629. // If there is red zone, restore FP directly, since SP has already been
  1630. // restored. Otherwise, restore the value of FP into ScratchReg.
  1631. if (HasRedZone || RBReg == SPReg)
  1632. BuildMI(MBB, MBBI, dl, LoadInst, FPReg)
  1633. .addImm(FPOffset)
  1634. .addReg(SPReg);
  1635. else
  1636. BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
  1637. .addImm(FPOffset)
  1638. .addReg(RBReg);
  1639. }
  1640. if (FI->usesPICBase())
  1641. BuildMI(MBB, MBBI, dl, LoadInst, PPC::R30)
  1642. .addImm(PBPOffset)
  1643. .addReg(RBReg);
  1644. if (HasBP)
  1645. BuildMI(MBB, MBBI, dl, LoadInst, BPReg)
  1646. .addImm(BPOffset)
  1647. .addReg(RBReg);
  1648. // There is nothing more to be loaded from the stack, so now we can
  1649. // restore SP: SP = RBReg + SPAdd.
  1650. if (RBReg != SPReg || SPAdd != 0) {
  1651. assert(!HasRedZone && "This should not happen with red zone");
  1652. // If SPAdd is 0, generate a copy.
  1653. if (SPAdd == 0)
  1654. BuildMI(MBB, MBBI, dl, OrInst, SPReg)
  1655. .addReg(RBReg)
  1656. .addReg(RBReg);
  1657. else
  1658. BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
  1659. .addReg(RBReg)
  1660. .addImm(SPAdd);
  1661. assert(RBReg != ScratchReg && "Should be using FP or SP as base register");
  1662. if (RBReg == FPReg)
  1663. BuildMI(MBB, MBBI, dl, OrInst, FPReg)
  1664. .addReg(ScratchReg)
  1665. .addReg(ScratchReg);
  1666. // Now load the LR from the caller's stack frame.
  1667. if (MustSaveLR && !LoadedLR)
  1668. BuildMI(MBB, MBBI, dl, LoadInst, ScratchReg)
  1669. .addImm(LROffset)
  1670. .addReg(SPReg);
  1671. }
  1672. if (MustSaveCR &&
  1673. !(SingleScratchReg && MustSaveLR))
  1674. for (unsigned i = 0, e = MustSaveCRs.size(); i != e; ++i)
  1675. BuildMI(MBB, MBBI, dl, MoveToCRInst, MustSaveCRs[i])
  1676. .addReg(TempReg, getKillRegState(i == e-1));
  1677. if (MustSaveLR) {
  1678. // If ROP protection is required, an extra instruction is added to compute a
  1679. // hash and then compare it to the hash stored in the prologue.
  1680. if (HasROPProtect) {
  1681. const int SaveIndex = FI->getROPProtectionHashSaveIndex();
  1682. const int64_t ImmOffset = MFI.getObjectOffset(SaveIndex);
  1683. assert((ImmOffset <= -8 && ImmOffset >= -512) &&
  1684. "ROP hash check location offset out of range.");
  1685. assert(((ImmOffset & 0x7) == 0) &&
  1686. "ROP hash check location offset must be 8 byte aligned.");
  1687. BuildMI(MBB, StackUpdateLoc, dl, HashChk)
  1688. .addReg(ScratchReg)
  1689. .addImm(ImmOffset)
  1690. .addReg(SPReg);
  1691. }
  1692. BuildMI(MBB, StackUpdateLoc, dl, MTLRInst).addReg(ScratchReg);
  1693. }
  1694. // Callee pop calling convention. Pop parameter/linkage area. Used for tail
  1695. // call optimization
  1696. if (IsReturnBlock) {
  1697. unsigned RetOpcode = MBBI->getOpcode();
  1698. if (MF.getTarget().Options.GuaranteedTailCallOpt &&
  1699. (RetOpcode == PPC::BLR || RetOpcode == PPC::BLR8) &&
  1700. MF.getFunction().getCallingConv() == CallingConv::Fast) {
  1701. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  1702. unsigned CallerAllocatedAmt = FI->getMinReservedArea();
  1703. if (CallerAllocatedAmt && isInt<16>(CallerAllocatedAmt)) {
  1704. BuildMI(MBB, MBBI, dl, AddImmInst, SPReg)
  1705. .addReg(SPReg).addImm(CallerAllocatedAmt);
  1706. } else {
  1707. BuildMI(MBB, MBBI, dl, LoadImmShiftedInst, ScratchReg)
  1708. .addImm(CallerAllocatedAmt >> 16);
  1709. BuildMI(MBB, MBBI, dl, OrImmInst, ScratchReg)
  1710. .addReg(ScratchReg, RegState::Kill)
  1711. .addImm(CallerAllocatedAmt & 0xFFFF);
  1712. BuildMI(MBB, MBBI, dl, AddInst)
  1713. .addReg(SPReg)
  1714. .addReg(FPReg)
  1715. .addReg(ScratchReg);
  1716. }
  1717. } else {
  1718. createTailCallBranchInstr(MBB);
  1719. }
  1720. }
  1721. }
  1722. void PPCFrameLowering::createTailCallBranchInstr(MachineBasicBlock &MBB) const {
  1723. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  1724. // If we got this far a first terminator should exist.
  1725. assert(MBBI != MBB.end() && "Failed to find the first terminator.");
  1726. DebugLoc dl = MBBI->getDebugLoc();
  1727. const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
  1728. // Create branch instruction for pseudo tail call return instruction.
  1729. // The TCRETURNdi variants are direct calls. Valid targets for those are
  1730. // MO_GlobalAddress operands as well as MO_ExternalSymbol with PC-Rel
  1731. // since we can tail call external functions with PC-Rel (i.e. we don't need
  1732. // to worry about different TOC pointers). Some of the external functions will
  1733. // be MO_GlobalAddress while others like memcpy for example, are going to
  1734. // be MO_ExternalSymbol.
  1735. unsigned RetOpcode = MBBI->getOpcode();
  1736. if (RetOpcode == PPC::TCRETURNdi) {
  1737. MBBI = MBB.getLastNonDebugInstr();
  1738. MachineOperand &JumpTarget = MBBI->getOperand(0);
  1739. if (JumpTarget.isGlobal())
  1740. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
  1741. addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
  1742. else if (JumpTarget.isSymbol())
  1743. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
  1744. addExternalSymbol(JumpTarget.getSymbolName());
  1745. else
  1746. llvm_unreachable("Expecting Global or External Symbol");
  1747. } else if (RetOpcode == PPC::TCRETURNri) {
  1748. MBBI = MBB.getLastNonDebugInstr();
  1749. assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
  1750. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
  1751. } else if (RetOpcode == PPC::TCRETURNai) {
  1752. MBBI = MBB.getLastNonDebugInstr();
  1753. MachineOperand &JumpTarget = MBBI->getOperand(0);
  1754. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
  1755. } else if (RetOpcode == PPC::TCRETURNdi8) {
  1756. MBBI = MBB.getLastNonDebugInstr();
  1757. MachineOperand &JumpTarget = MBBI->getOperand(0);
  1758. if (JumpTarget.isGlobal())
  1759. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
  1760. addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
  1761. else if (JumpTarget.isSymbol())
  1762. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
  1763. addExternalSymbol(JumpTarget.getSymbolName());
  1764. else
  1765. llvm_unreachable("Expecting Global or External Symbol");
  1766. } else if (RetOpcode == PPC::TCRETURNri8) {
  1767. MBBI = MBB.getLastNonDebugInstr();
  1768. assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
  1769. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
  1770. } else if (RetOpcode == PPC::TCRETURNai8) {
  1771. MBBI = MBB.getLastNonDebugInstr();
  1772. MachineOperand &JumpTarget = MBBI->getOperand(0);
  1773. BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
  1774. }
  1775. }
  1776. void PPCFrameLowering::determineCalleeSaves(MachineFunction &MF,
  1777. BitVector &SavedRegs,
  1778. RegScavenger *RS) const {
  1779. TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
  1780. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  1781. // Save and clear the LR state.
  1782. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  1783. unsigned LR = RegInfo->getRARegister();
  1784. FI->setMustSaveLR(MustSaveLR(MF, LR));
  1785. SavedRegs.reset(LR);
  1786. // Save R31 if necessary
  1787. int FPSI = FI->getFramePointerSaveIndex();
  1788. const bool isPPC64 = Subtarget.isPPC64();
  1789. MachineFrameInfo &MFI = MF.getFrameInfo();
  1790. // If the frame pointer save index hasn't been defined yet.
  1791. if (!FPSI && needsFP(MF)) {
  1792. // Find out what the fix offset of the frame pointer save area.
  1793. int FPOffset = getFramePointerSaveOffset();
  1794. // Allocate the frame index for frame pointer save area.
  1795. FPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
  1796. // Save the result.
  1797. FI->setFramePointerSaveIndex(FPSI);
  1798. }
  1799. int BPSI = FI->getBasePointerSaveIndex();
  1800. if (!BPSI && RegInfo->hasBasePointer(MF)) {
  1801. int BPOffset = getBasePointerSaveOffset();
  1802. // Allocate the frame index for the base pointer save area.
  1803. BPSI = MFI.CreateFixedObject(isPPC64? 8 : 4, BPOffset, true);
  1804. // Save the result.
  1805. FI->setBasePointerSaveIndex(BPSI);
  1806. }
  1807. // Reserve stack space for the PIC Base register (R30).
  1808. // Only used in SVR4 32-bit.
  1809. if (FI->usesPICBase()) {
  1810. int PBPSI = MFI.CreateFixedObject(4, -8, true);
  1811. FI->setPICBasePointerSaveIndex(PBPSI);
  1812. }
  1813. // Make sure we don't explicitly spill r31, because, for example, we have
  1814. // some inline asm which explicitly clobbers it, when we otherwise have a
  1815. // frame pointer and are using r31's spill slot for the prologue/epilogue
  1816. // code. Same goes for the base pointer and the PIC base register.
  1817. if (needsFP(MF))
  1818. SavedRegs.reset(isPPC64 ? PPC::X31 : PPC::R31);
  1819. if (RegInfo->hasBasePointer(MF))
  1820. SavedRegs.reset(RegInfo->getBaseRegister(MF));
  1821. if (FI->usesPICBase())
  1822. SavedRegs.reset(PPC::R30);
  1823. // Reserve stack space to move the linkage area to in case of a tail call.
  1824. int TCSPDelta = 0;
  1825. if (MF.getTarget().Options.GuaranteedTailCallOpt &&
  1826. (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
  1827. MFI.CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
  1828. }
  1829. // Allocate the nonvolatile CR spill slot iff the function uses CR 2, 3, or 4.
  1830. // For 64-bit SVR4, and all flavors of AIX we create a FixedStack
  1831. // object at the offset of the CR-save slot in the linkage area. The actual
  1832. // save and restore of the condition register will be created as part of the
  1833. // prologue and epilogue insertion, but the FixedStack object is needed to
  1834. // keep the CalleSavedInfo valid.
  1835. if ((SavedRegs.test(PPC::CR2) || SavedRegs.test(PPC::CR3) ||
  1836. SavedRegs.test(PPC::CR4))) {
  1837. const uint64_t SpillSize = 4; // Condition register is always 4 bytes.
  1838. const int64_t SpillOffset =
  1839. Subtarget.isPPC64() ? 8 : Subtarget.isAIXABI() ? 4 : -4;
  1840. int FrameIdx =
  1841. MFI.CreateFixedObject(SpillSize, SpillOffset,
  1842. /* IsImmutable */ true, /* IsAliased */ false);
  1843. FI->setCRSpillFrameIndex(FrameIdx);
  1844. }
  1845. }
  1846. void PPCFrameLowering::processFunctionBeforeFrameFinalized(MachineFunction &MF,
  1847. RegScavenger *RS) const {
  1848. // Get callee saved register information.
  1849. MachineFrameInfo &MFI = MF.getFrameInfo();
  1850. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  1851. // If the function is shrink-wrapped, and if the function has a tail call, the
  1852. // tail call might not be in the new RestoreBlock, so real branch instruction
  1853. // won't be generated by emitEpilogue(), because shrink-wrap has chosen new
  1854. // RestoreBlock. So we handle this case here.
  1855. if (MFI.getSavePoint() && MFI.hasTailCall()) {
  1856. MachineBasicBlock *RestoreBlock = MFI.getRestorePoint();
  1857. for (MachineBasicBlock &MBB : MF) {
  1858. if (MBB.isReturnBlock() && (&MBB) != RestoreBlock)
  1859. createTailCallBranchInstr(MBB);
  1860. }
  1861. }
  1862. // Early exit if no callee saved registers are modified!
  1863. if (CSI.empty() && !needsFP(MF)) {
  1864. addScavengingSpillSlot(MF, RS);
  1865. return;
  1866. }
  1867. unsigned MinGPR = PPC::R31;
  1868. unsigned MinG8R = PPC::X31;
  1869. unsigned MinFPR = PPC::F31;
  1870. unsigned MinVR = Subtarget.hasSPE() ? PPC::S31 : PPC::V31;
  1871. bool HasGPSaveArea = false;
  1872. bool HasG8SaveArea = false;
  1873. bool HasFPSaveArea = false;
  1874. bool HasVRSaveArea = false;
  1875. SmallVector<CalleeSavedInfo, 18> GPRegs;
  1876. SmallVector<CalleeSavedInfo, 18> G8Regs;
  1877. SmallVector<CalleeSavedInfo, 18> FPRegs;
  1878. SmallVector<CalleeSavedInfo, 18> VRegs;
  1879. for (const CalleeSavedInfo &I : CSI) {
  1880. Register Reg = I.getReg();
  1881. assert((!MF.getInfo<PPCFunctionInfo>()->mustSaveTOC() ||
  1882. (Reg != PPC::X2 && Reg != PPC::R2)) &&
  1883. "Not expecting to try to spill R2 in a function that must save TOC");
  1884. if (PPC::GPRCRegClass.contains(Reg)) {
  1885. HasGPSaveArea = true;
  1886. GPRegs.push_back(I);
  1887. if (Reg < MinGPR) {
  1888. MinGPR = Reg;
  1889. }
  1890. } else if (PPC::G8RCRegClass.contains(Reg)) {
  1891. HasG8SaveArea = true;
  1892. G8Regs.push_back(I);
  1893. if (Reg < MinG8R) {
  1894. MinG8R = Reg;
  1895. }
  1896. } else if (PPC::F8RCRegClass.contains(Reg)) {
  1897. HasFPSaveArea = true;
  1898. FPRegs.push_back(I);
  1899. if (Reg < MinFPR) {
  1900. MinFPR = Reg;
  1901. }
  1902. } else if (PPC::CRBITRCRegClass.contains(Reg) ||
  1903. PPC::CRRCRegClass.contains(Reg)) {
  1904. ; // do nothing, as we already know whether CRs are spilled
  1905. } else if (PPC::VRRCRegClass.contains(Reg) ||
  1906. PPC::SPERCRegClass.contains(Reg)) {
  1907. // Altivec and SPE are mutually exclusive, but have the same stack
  1908. // alignment requirements, so overload the save area for both cases.
  1909. HasVRSaveArea = true;
  1910. VRegs.push_back(I);
  1911. if (Reg < MinVR) {
  1912. MinVR = Reg;
  1913. }
  1914. } else {
  1915. llvm_unreachable("Unknown RegisterClass!");
  1916. }
  1917. }
  1918. PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
  1919. const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
  1920. int64_t LowerBound = 0;
  1921. // Take into account stack space reserved for tail calls.
  1922. int TCSPDelta = 0;
  1923. if (MF.getTarget().Options.GuaranteedTailCallOpt &&
  1924. (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
  1925. LowerBound = TCSPDelta;
  1926. }
  1927. // The Floating-point register save area is right below the back chain word
  1928. // of the previous stack frame.
  1929. if (HasFPSaveArea) {
  1930. for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
  1931. int FI = FPRegs[i].getFrameIdx();
  1932. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  1933. }
  1934. LowerBound -= (31 - TRI->getEncodingValue(MinFPR) + 1) * 8;
  1935. }
  1936. // Check whether the frame pointer register is allocated. If so, make sure it
  1937. // is spilled to the correct offset.
  1938. if (needsFP(MF)) {
  1939. int FI = PFI->getFramePointerSaveIndex();
  1940. assert(FI && "No Frame Pointer Save Slot!");
  1941. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  1942. // FP is R31/X31, so no need to update MinGPR/MinG8R.
  1943. HasGPSaveArea = true;
  1944. }
  1945. if (PFI->usesPICBase()) {
  1946. int FI = PFI->getPICBasePointerSaveIndex();
  1947. assert(FI && "No PIC Base Pointer Save Slot!");
  1948. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  1949. MinGPR = std::min<unsigned>(MinGPR, PPC::R30);
  1950. HasGPSaveArea = true;
  1951. }
  1952. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  1953. if (RegInfo->hasBasePointer(MF)) {
  1954. int FI = PFI->getBasePointerSaveIndex();
  1955. assert(FI && "No Base Pointer Save Slot!");
  1956. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  1957. Register BP = RegInfo->getBaseRegister(MF);
  1958. if (PPC::G8RCRegClass.contains(BP)) {
  1959. MinG8R = std::min<unsigned>(MinG8R, BP);
  1960. HasG8SaveArea = true;
  1961. } else if (PPC::GPRCRegClass.contains(BP)) {
  1962. MinGPR = std::min<unsigned>(MinGPR, BP);
  1963. HasGPSaveArea = true;
  1964. }
  1965. }
  1966. // General register save area starts right below the Floating-point
  1967. // register save area.
  1968. if (HasGPSaveArea || HasG8SaveArea) {
  1969. // Move general register save area spill slots down, taking into account
  1970. // the size of the Floating-point register save area.
  1971. for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
  1972. if (!GPRegs[i].isSpilledToReg()) {
  1973. int FI = GPRegs[i].getFrameIdx();
  1974. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  1975. }
  1976. }
  1977. // Move general register save area spill slots down, taking into account
  1978. // the size of the Floating-point register save area.
  1979. for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
  1980. if (!G8Regs[i].isSpilledToReg()) {
  1981. int FI = G8Regs[i].getFrameIdx();
  1982. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  1983. }
  1984. }
  1985. unsigned MinReg =
  1986. std::min<unsigned>(TRI->getEncodingValue(MinGPR),
  1987. TRI->getEncodingValue(MinG8R));
  1988. const unsigned GPRegSize = Subtarget.isPPC64() ? 8 : 4;
  1989. LowerBound -= (31 - MinReg + 1) * GPRegSize;
  1990. }
  1991. // For 32-bit only, the CR save area is below the general register
  1992. // save area. For 64-bit SVR4, the CR save area is addressed relative
  1993. // to the stack pointer and hence does not need an adjustment here.
  1994. // Only CR2 (the first nonvolatile spilled) has an associated frame
  1995. // index so that we have a single uniform save area.
  1996. if (spillsCR(MF) && Subtarget.is32BitELFABI()) {
  1997. // Adjust the frame index of the CR spill slot.
  1998. for (const auto &CSInfo : CSI) {
  1999. if (CSInfo.getReg() == PPC::CR2) {
  2000. int FI = CSInfo.getFrameIdx();
  2001. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  2002. break;
  2003. }
  2004. }
  2005. LowerBound -= 4; // The CR save area is always 4 bytes long.
  2006. }
  2007. // Both Altivec and SPE have the same alignment and padding requirements
  2008. // within the stack frame.
  2009. if (HasVRSaveArea) {
  2010. // Insert alignment padding, we need 16-byte alignment. Note: for positive
  2011. // number the alignment formula is : y = (x + (n-1)) & (~(n-1)). But since
  2012. // we are using negative number here (the stack grows downward). We should
  2013. // use formula : y = x & (~(n-1)). Where x is the size before aligning, n
  2014. // is the alignment size ( n = 16 here) and y is the size after aligning.
  2015. assert(LowerBound <= 0 && "Expect LowerBound have a non-positive value!");
  2016. LowerBound &= ~(15);
  2017. for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
  2018. int FI = VRegs[i].getFrameIdx();
  2019. MFI.setObjectOffset(FI, LowerBound + MFI.getObjectOffset(FI));
  2020. }
  2021. }
  2022. addScavengingSpillSlot(MF, RS);
  2023. }
  2024. void
  2025. PPCFrameLowering::addScavengingSpillSlot(MachineFunction &MF,
  2026. RegScavenger *RS) const {
  2027. // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
  2028. // a large stack, which will require scavenging a register to materialize a
  2029. // large offset.
  2030. // We need to have a scavenger spill slot for spills if the frame size is
  2031. // large. In case there is no free register for large-offset addressing,
  2032. // this slot is used for the necessary emergency spill. Also, we need the
  2033. // slot for dynamic stack allocations.
  2034. // The scavenger might be invoked if the frame offset does not fit into
  2035. // the 16-bit immediate. We don't know the complete frame size here
  2036. // because we've not yet computed callee-saved register spills or the
  2037. // needed alignment padding.
  2038. unsigned StackSize = determineFrameLayout(MF, true);
  2039. MachineFrameInfo &MFI = MF.getFrameInfo();
  2040. if (MFI.hasVarSizedObjects() || spillsCR(MF) || hasNonRISpills(MF) ||
  2041. (hasSpills(MF) && !isInt<16>(StackSize))) {
  2042. const TargetRegisterClass &GPRC = PPC::GPRCRegClass;
  2043. const TargetRegisterClass &G8RC = PPC::G8RCRegClass;
  2044. const TargetRegisterClass &RC = Subtarget.isPPC64() ? G8RC : GPRC;
  2045. const TargetRegisterInfo &TRI = *Subtarget.getRegisterInfo();
  2046. unsigned Size = TRI.getSpillSize(RC);
  2047. Align Alignment = TRI.getSpillAlign(RC);
  2048. RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Alignment, false));
  2049. // Might we have over-aligned allocas?
  2050. bool HasAlVars =
  2051. MFI.hasVarSizedObjects() && MFI.getMaxAlign() > getStackAlign();
  2052. // These kinds of spills might need two registers.
  2053. if (spillsCR(MF) || HasAlVars)
  2054. RS->addScavengingFrameIndex(
  2055. MFI.CreateStackObject(Size, Alignment, false));
  2056. }
  2057. }
  2058. // This function checks if a callee saved gpr can be spilled to a volatile
  2059. // vector register. This occurs for leaf functions when the option
  2060. // ppc-enable-pe-vector-spills is enabled. If there are any remaining registers
  2061. // which were not spilled to vectors, return false so the target independent
  2062. // code can handle them by assigning a FrameIdx to a stack slot.
  2063. bool PPCFrameLowering::assignCalleeSavedSpillSlots(
  2064. MachineFunction &MF, const TargetRegisterInfo *TRI,
  2065. std::vector<CalleeSavedInfo> &CSI) const {
  2066. if (CSI.empty())
  2067. return true; // Early exit if no callee saved registers are modified!
  2068. // Early exit if cannot spill gprs to volatile vector registers.
  2069. MachineFrameInfo &MFI = MF.getFrameInfo();
  2070. if (!EnablePEVectorSpills || MFI.hasCalls() || !Subtarget.hasP9Vector())
  2071. return false;
  2072. // Build a BitVector of VSRs that can be used for spilling GPRs.
  2073. BitVector BVAllocatable = TRI->getAllocatableSet(MF);
  2074. BitVector BVCalleeSaved(TRI->getNumRegs());
  2075. const PPCRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  2076. const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
  2077. for (unsigned i = 0; CSRegs[i]; ++i)
  2078. BVCalleeSaved.set(CSRegs[i]);
  2079. for (unsigned Reg : BVAllocatable.set_bits()) {
  2080. // Set to 0 if the register is not a volatile VSX register, or if it is
  2081. // used in the function.
  2082. if (BVCalleeSaved[Reg] || !PPC::VSRCRegClass.contains(Reg) ||
  2083. MF.getRegInfo().isPhysRegUsed(Reg))
  2084. BVAllocatable.reset(Reg);
  2085. }
  2086. bool AllSpilledToReg = true;
  2087. unsigned LastVSRUsedForSpill = 0;
  2088. for (auto &CS : CSI) {
  2089. if (BVAllocatable.none())
  2090. return false;
  2091. Register Reg = CS.getReg();
  2092. if (!PPC::G8RCRegClass.contains(Reg)) {
  2093. AllSpilledToReg = false;
  2094. continue;
  2095. }
  2096. // For P9, we can reuse LastVSRUsedForSpill to spill two GPRs
  2097. // into one VSR using the mtvsrdd instruction.
  2098. if (LastVSRUsedForSpill != 0) {
  2099. CS.setDstReg(LastVSRUsedForSpill);
  2100. BVAllocatable.reset(LastVSRUsedForSpill);
  2101. LastVSRUsedForSpill = 0;
  2102. continue;
  2103. }
  2104. unsigned VolatileVFReg = BVAllocatable.find_first();
  2105. if (VolatileVFReg < BVAllocatable.size()) {
  2106. CS.setDstReg(VolatileVFReg);
  2107. LastVSRUsedForSpill = VolatileVFReg;
  2108. } else {
  2109. AllSpilledToReg = false;
  2110. }
  2111. }
  2112. return AllSpilledToReg;
  2113. }
  2114. bool PPCFrameLowering::spillCalleeSavedRegisters(
  2115. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  2116. ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  2117. MachineFunction *MF = MBB.getParent();
  2118. const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
  2119. PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
  2120. bool MustSaveTOC = FI->mustSaveTOC();
  2121. DebugLoc DL;
  2122. bool CRSpilled = false;
  2123. MachineInstrBuilder CRMIB;
  2124. BitVector Spilled(TRI->getNumRegs());
  2125. VSRContainingGPRs.clear();
  2126. // Map each VSR to GPRs to be spilled with into it. Single VSR can contain one
  2127. // or two GPRs, so we need table to record information for later save/restore.
  2128. llvm::for_each(CSI, [&](const CalleeSavedInfo &Info) {
  2129. if (Info.isSpilledToReg()) {
  2130. auto &SpilledVSR =
  2131. VSRContainingGPRs.FindAndConstruct(Info.getDstReg()).second;
  2132. assert(SpilledVSR.second == 0 &&
  2133. "Can't spill more than two GPRs into VSR!");
  2134. if (SpilledVSR.first == 0)
  2135. SpilledVSR.first = Info.getReg();
  2136. else
  2137. SpilledVSR.second = Info.getReg();
  2138. }
  2139. });
  2140. for (const CalleeSavedInfo &I : CSI) {
  2141. Register Reg = I.getReg();
  2142. // CR2 through CR4 are the nonvolatile CR fields.
  2143. bool IsCRField = PPC::CR2 <= Reg && Reg <= PPC::CR4;
  2144. // Add the callee-saved register as live-in; it's killed at the spill.
  2145. // Do not do this for callee-saved registers that are live-in to the
  2146. // function because they will already be marked live-in and this will be
  2147. // adding it for a second time. It is an error to add the same register
  2148. // to the set more than once.
  2149. const MachineRegisterInfo &MRI = MF->getRegInfo();
  2150. bool IsLiveIn = MRI.isLiveIn(Reg);
  2151. if (!IsLiveIn)
  2152. MBB.addLiveIn(Reg);
  2153. if (CRSpilled && IsCRField) {
  2154. CRMIB.addReg(Reg, RegState::ImplicitKill);
  2155. continue;
  2156. }
  2157. // The actual spill will happen in the prologue.
  2158. if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
  2159. continue;
  2160. // Insert the spill to the stack frame.
  2161. if (IsCRField) {
  2162. PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>();
  2163. if (!Subtarget.is32BitELFABI()) {
  2164. // The actual spill will happen at the start of the prologue.
  2165. FuncInfo->addMustSaveCR(Reg);
  2166. } else {
  2167. CRSpilled = true;
  2168. FuncInfo->setSpillsCR();
  2169. // 32-bit: FP-relative. Note that we made sure CR2-CR4 all have
  2170. // the same frame index in PPCRegisterInfo::hasReservedSpillSlot.
  2171. CRMIB = BuildMI(*MF, DL, TII.get(PPC::MFCR), PPC::R12)
  2172. .addReg(Reg, RegState::ImplicitKill);
  2173. MBB.insert(MI, CRMIB);
  2174. MBB.insert(MI, addFrameReference(BuildMI(*MF, DL, TII.get(PPC::STW))
  2175. .addReg(PPC::R12,
  2176. getKillRegState(true)),
  2177. I.getFrameIdx()));
  2178. }
  2179. } else {
  2180. if (I.isSpilledToReg()) {
  2181. unsigned Dst = I.getDstReg();
  2182. if (Spilled[Dst])
  2183. continue;
  2184. if (VSRContainingGPRs[Dst].second != 0) {
  2185. assert(Subtarget.hasP9Vector() &&
  2186. "mtvsrdd is unavailable on pre-P9 targets.");
  2187. NumPESpillVSR += 2;
  2188. BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRDD), Dst)
  2189. .addReg(VSRContainingGPRs[Dst].first, getKillRegState(true))
  2190. .addReg(VSRContainingGPRs[Dst].second, getKillRegState(true));
  2191. } else if (VSRContainingGPRs[Dst].second == 0) {
  2192. assert(Subtarget.hasP8Vector() &&
  2193. "Can't move GPR to VSR on pre-P8 targets.");
  2194. ++NumPESpillVSR;
  2195. BuildMI(MBB, MI, DL, TII.get(PPC::MTVSRD),
  2196. TRI->getSubReg(Dst, PPC::sub_64))
  2197. .addReg(VSRContainingGPRs[Dst].first, getKillRegState(true));
  2198. } else {
  2199. llvm_unreachable("More than two GPRs spilled to a VSR!");
  2200. }
  2201. Spilled.set(Dst);
  2202. } else {
  2203. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  2204. // Use !IsLiveIn for the kill flag.
  2205. // We do not want to kill registers that are live in this function
  2206. // before their use because they will become undefined registers.
  2207. // Functions without NoUnwind need to preserve the order of elements in
  2208. // saved vector registers.
  2209. if (Subtarget.needsSwapsForVSXMemOps() &&
  2210. !MF->getFunction().hasFnAttribute(Attribute::NoUnwind))
  2211. TII.storeRegToStackSlotNoUpd(MBB, MI, Reg, !IsLiveIn,
  2212. I.getFrameIdx(), RC, TRI);
  2213. else
  2214. TII.storeRegToStackSlot(MBB, MI, Reg, !IsLiveIn, I.getFrameIdx(),
  2215. RC, TRI);
  2216. }
  2217. }
  2218. }
  2219. return true;
  2220. }
  2221. static void restoreCRs(bool is31, bool CR2Spilled, bool CR3Spilled,
  2222. bool CR4Spilled, MachineBasicBlock &MBB,
  2223. MachineBasicBlock::iterator MI,
  2224. ArrayRef<CalleeSavedInfo> CSI, unsigned CSIIndex) {
  2225. MachineFunction *MF = MBB.getParent();
  2226. const PPCInstrInfo &TII = *MF->getSubtarget<PPCSubtarget>().getInstrInfo();
  2227. DebugLoc DL;
  2228. unsigned MoveReg = PPC::R12;
  2229. // 32-bit: FP-relative
  2230. MBB.insert(MI,
  2231. addFrameReference(BuildMI(*MF, DL, TII.get(PPC::LWZ), MoveReg),
  2232. CSI[CSIIndex].getFrameIdx()));
  2233. unsigned RestoreOp = PPC::MTOCRF;
  2234. if (CR2Spilled)
  2235. MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR2)
  2236. .addReg(MoveReg, getKillRegState(!CR3Spilled && !CR4Spilled)));
  2237. if (CR3Spilled)
  2238. MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR3)
  2239. .addReg(MoveReg, getKillRegState(!CR4Spilled)));
  2240. if (CR4Spilled)
  2241. MBB.insert(MI, BuildMI(*MF, DL, TII.get(RestoreOp), PPC::CR4)
  2242. .addReg(MoveReg, getKillRegState(true)));
  2243. }
  2244. MachineBasicBlock::iterator PPCFrameLowering::
  2245. eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
  2246. MachineBasicBlock::iterator I) const {
  2247. const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
  2248. if (MF.getTarget().Options.GuaranteedTailCallOpt &&
  2249. I->getOpcode() == PPC::ADJCALLSTACKUP) {
  2250. // Add (actually subtract) back the amount the callee popped on return.
  2251. if (int CalleeAmt = I->getOperand(1).getImm()) {
  2252. bool is64Bit = Subtarget.isPPC64();
  2253. CalleeAmt *= -1;
  2254. unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
  2255. unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
  2256. unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
  2257. unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
  2258. unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
  2259. unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
  2260. const DebugLoc &dl = I->getDebugLoc();
  2261. if (isInt<16>(CalleeAmt)) {
  2262. BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
  2263. .addReg(StackReg, RegState::Kill)
  2264. .addImm(CalleeAmt);
  2265. } else {
  2266. MachineBasicBlock::iterator MBBI = I;
  2267. BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
  2268. .addImm(CalleeAmt >> 16);
  2269. BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
  2270. .addReg(TmpReg, RegState::Kill)
  2271. .addImm(CalleeAmt & 0xFFFF);
  2272. BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
  2273. .addReg(StackReg, RegState::Kill)
  2274. .addReg(TmpReg);
  2275. }
  2276. }
  2277. }
  2278. // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
  2279. return MBB.erase(I);
  2280. }
  2281. static bool isCalleeSavedCR(unsigned Reg) {
  2282. return PPC::CR2 == Reg || Reg == PPC::CR3 || Reg == PPC::CR4;
  2283. }
  2284. bool PPCFrameLowering::restoreCalleeSavedRegisters(
  2285. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  2286. MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  2287. MachineFunction *MF = MBB.getParent();
  2288. const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
  2289. PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
  2290. bool MustSaveTOC = FI->mustSaveTOC();
  2291. bool CR2Spilled = false;
  2292. bool CR3Spilled = false;
  2293. bool CR4Spilled = false;
  2294. unsigned CSIIndex = 0;
  2295. BitVector Restored(TRI->getNumRegs());
  2296. // Initialize insertion-point logic; we will be restoring in reverse
  2297. // order of spill.
  2298. MachineBasicBlock::iterator I = MI, BeforeI = I;
  2299. bool AtStart = I == MBB.begin();
  2300. if (!AtStart)
  2301. --BeforeI;
  2302. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  2303. Register Reg = CSI[i].getReg();
  2304. if ((Reg == PPC::X2 || Reg == PPC::R2) && MustSaveTOC)
  2305. continue;
  2306. // Restore of callee saved condition register field is handled during
  2307. // epilogue insertion.
  2308. if (isCalleeSavedCR(Reg) && !Subtarget.is32BitELFABI())
  2309. continue;
  2310. if (Reg == PPC::CR2) {
  2311. CR2Spilled = true;
  2312. // The spill slot is associated only with CR2, which is the
  2313. // first nonvolatile spilled. Save it here.
  2314. CSIIndex = i;
  2315. continue;
  2316. } else if (Reg == PPC::CR3) {
  2317. CR3Spilled = true;
  2318. continue;
  2319. } else if (Reg == PPC::CR4) {
  2320. CR4Spilled = true;
  2321. continue;
  2322. } else {
  2323. // On 32-bit ELF when we first encounter a non-CR register after seeing at
  2324. // least one CR register, restore all spilled CRs together.
  2325. if (CR2Spilled || CR3Spilled || CR4Spilled) {
  2326. bool is31 = needsFP(*MF);
  2327. restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI,
  2328. CSIIndex);
  2329. CR2Spilled = CR3Spilled = CR4Spilled = false;
  2330. }
  2331. if (CSI[i].isSpilledToReg()) {
  2332. DebugLoc DL;
  2333. unsigned Dst = CSI[i].getDstReg();
  2334. if (Restored[Dst])
  2335. continue;
  2336. if (VSRContainingGPRs[Dst].second != 0) {
  2337. assert(Subtarget.hasP9Vector());
  2338. NumPEReloadVSR += 2;
  2339. BuildMI(MBB, I, DL, TII.get(PPC::MFVSRLD),
  2340. VSRContainingGPRs[Dst].second)
  2341. .addReg(Dst);
  2342. BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD),
  2343. VSRContainingGPRs[Dst].first)
  2344. .addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));
  2345. } else if (VSRContainingGPRs[Dst].second == 0) {
  2346. assert(Subtarget.hasP8Vector());
  2347. ++NumPEReloadVSR;
  2348. BuildMI(MBB, I, DL, TII.get(PPC::MFVSRD),
  2349. VSRContainingGPRs[Dst].first)
  2350. .addReg(TRI->getSubReg(Dst, PPC::sub_64), getKillRegState(true));
  2351. } else {
  2352. llvm_unreachable("More than two GPRs spilled to a VSR!");
  2353. }
  2354. Restored.set(Dst);
  2355. } else {
  2356. // Default behavior for non-CR saves.
  2357. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  2358. // Functions without NoUnwind need to preserve the order of elements in
  2359. // saved vector registers.
  2360. if (Subtarget.needsSwapsForVSXMemOps() &&
  2361. !MF->getFunction().hasFnAttribute(Attribute::NoUnwind))
  2362. TII.loadRegFromStackSlotNoUpd(MBB, I, Reg, CSI[i].getFrameIdx(), RC,
  2363. TRI);
  2364. else
  2365. TII.loadRegFromStackSlot(MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
  2366. assert(I != MBB.begin() &&
  2367. "loadRegFromStackSlot didn't insert any code!");
  2368. }
  2369. }
  2370. // Insert in reverse order.
  2371. if (AtStart)
  2372. I = MBB.begin();
  2373. else {
  2374. I = BeforeI;
  2375. ++I;
  2376. }
  2377. }
  2378. // If we haven't yet spilled the CRs, do so now.
  2379. if (CR2Spilled || CR3Spilled || CR4Spilled) {
  2380. assert(Subtarget.is32BitELFABI() &&
  2381. "Only set CR[2|3|4]Spilled on 32-bit SVR4.");
  2382. bool is31 = needsFP(*MF);
  2383. restoreCRs(is31, CR2Spilled, CR3Spilled, CR4Spilled, MBB, I, CSI, CSIIndex);
  2384. }
  2385. return true;
  2386. }
  2387. uint64_t PPCFrameLowering::getTOCSaveOffset() const {
  2388. return TOCSaveOffset;
  2389. }
  2390. uint64_t PPCFrameLowering::getFramePointerSaveOffset() const {
  2391. return FramePointerSaveOffset;
  2392. }
  2393. uint64_t PPCFrameLowering::getBasePointerSaveOffset() const {
  2394. return BasePointerSaveOffset;
  2395. }
  2396. bool PPCFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
  2397. if (MF.getInfo<PPCFunctionInfo>()->shrinkWrapDisabled())
  2398. return false;
  2399. return !MF.getSubtarget<PPCSubtarget>().is32BitELFABI();
  2400. }