AArch64FrameLowering.cpp 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961
  1. //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
  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 AArch64 implementation of TargetFrameLowering class.
  10. //
  11. // On AArch64, stack frames are structured as follows:
  12. //
  13. // The stack grows downward.
  14. //
  15. // All of the individual frame areas on the frame below are optional, i.e. it's
  16. // possible to create a function so that the particular area isn't present
  17. // in the frame.
  18. //
  19. // At function entry, the "frame" looks as follows:
  20. //
  21. // | | Higher address
  22. // |-----------------------------------|
  23. // | |
  24. // | arguments passed on the stack |
  25. // | |
  26. // |-----------------------------------| <- sp
  27. // | | Lower address
  28. //
  29. //
  30. // After the prologue has run, the frame has the following general structure.
  31. // Note that this doesn't depict the case where a red-zone is used. Also,
  32. // technically the last frame area (VLAs) doesn't get created until in the
  33. // main function body, after the prologue is run. However, it's depicted here
  34. // for completeness.
  35. //
  36. // | | Higher address
  37. // |-----------------------------------|
  38. // | |
  39. // | arguments passed on the stack |
  40. // | |
  41. // |-----------------------------------|
  42. // | |
  43. // | (Win64 only) varargs from reg |
  44. // | |
  45. // |-----------------------------------|
  46. // | |
  47. // | callee-saved gpr registers | <--.
  48. // | | | On Darwin platforms these
  49. // |- - - - - - - - - - - - - - - - - -| | callee saves are swapped,
  50. // | prev_lr | | (frame record first)
  51. // | prev_fp | <--'
  52. // | async context if needed |
  53. // | (a.k.a. "frame record") |
  54. // |-----------------------------------| <- fp(=x29)
  55. // | |
  56. // | callee-saved fp/simd/SVE regs |
  57. // | |
  58. // |-----------------------------------|
  59. // | |
  60. // | SVE stack objects |
  61. // | |
  62. // |-----------------------------------|
  63. // |.empty.space.to.make.part.below....|
  64. // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
  65. // |.the.standard.16-byte.alignment....| compile time; if present)
  66. // |-----------------------------------|
  67. // | |
  68. // | local variables of fixed size |
  69. // | including spill slots |
  70. // |-----------------------------------| <- bp(not defined by ABI,
  71. // |.variable-sized.local.variables....| LLVM chooses X19)
  72. // |.(VLAs)............................| (size of this area is unknown at
  73. // |...................................| compile time)
  74. // |-----------------------------------| <- sp
  75. // | | Lower address
  76. //
  77. //
  78. // To access the data in a frame, at-compile time, a constant offset must be
  79. // computable from one of the pointers (fp, bp, sp) to access it. The size
  80. // of the areas with a dotted background cannot be computed at compile-time
  81. // if they are present, making it required to have all three of fp, bp and
  82. // sp to be set up to be able to access all contents in the frame areas,
  83. // assuming all of the frame areas are non-empty.
  84. //
  85. // For most functions, some of the frame areas are empty. For those functions,
  86. // it may not be necessary to set up fp or bp:
  87. // * A base pointer is definitely needed when there are both VLAs and local
  88. // variables with more-than-default alignment requirements.
  89. // * A frame pointer is definitely needed when there are local variables with
  90. // more-than-default alignment requirements.
  91. //
  92. // For Darwin platforms the frame-record (fp, lr) is stored at the top of the
  93. // callee-saved area, since the unwind encoding does not allow for encoding
  94. // this dynamically and existing tools depend on this layout. For other
  95. // platforms, the frame-record is stored at the bottom of the (gpr) callee-saved
  96. // area to allow SVE stack objects (allocated directly below the callee-saves,
  97. // if available) to be accessed directly from the framepointer.
  98. // The SVE spill/fill instructions have VL-scaled addressing modes such
  99. // as:
  100. // ldr z8, [fp, #-7 mul vl]
  101. // For SVE the size of the vector length (VL) is not known at compile-time, so
  102. // '#-7 mul vl' is an offset that can only be evaluated at runtime. With this
  103. // layout, we don't need to add an unscaled offset to the framepointer before
  104. // accessing the SVE object in the frame.
  105. //
  106. // In some cases when a base pointer is not strictly needed, it is generated
  107. // anyway when offsets from the frame pointer to access local variables become
  108. // so large that the offset can't be encoded in the immediate fields of loads
  109. // or stores.
  110. //
  111. // Outgoing function arguments must be at the bottom of the stack frame when
  112. // calling another function. If we do not have variable-sized stack objects, we
  113. // can allocate a "reserved call frame" area at the bottom of the local
  114. // variable area, large enough for all outgoing calls. If we do have VLAs, then
  115. // the stack pointer must be decremented and incremented around each call to
  116. // make space for the arguments below the VLAs.
  117. //
  118. // FIXME: also explain the redzone concept.
  119. //
  120. // An example of the prologue:
  121. //
  122. // .globl __foo
  123. // .align 2
  124. // __foo:
  125. // Ltmp0:
  126. // .cfi_startproc
  127. // .cfi_personality 155, ___gxx_personality_v0
  128. // Leh_func_begin:
  129. // .cfi_lsda 16, Lexception33
  130. //
  131. // stp xa,bx, [sp, -#offset]!
  132. // ...
  133. // stp x28, x27, [sp, #offset-32]
  134. // stp fp, lr, [sp, #offset-16]
  135. // add fp, sp, #offset - 16
  136. // sub sp, sp, #1360
  137. //
  138. // The Stack:
  139. // +-------------------------------------------+
  140. // 10000 | ........ | ........ | ........ | ........ |
  141. // 10004 | ........ | ........ | ........ | ........ |
  142. // +-------------------------------------------+
  143. // 10008 | ........ | ........ | ........ | ........ |
  144. // 1000c | ........ | ........ | ........ | ........ |
  145. // +===========================================+
  146. // 10010 | X28 Register |
  147. // 10014 | X28 Register |
  148. // +-------------------------------------------+
  149. // 10018 | X27 Register |
  150. // 1001c | X27 Register |
  151. // +===========================================+
  152. // 10020 | Frame Pointer |
  153. // 10024 | Frame Pointer |
  154. // +-------------------------------------------+
  155. // 10028 | Link Register |
  156. // 1002c | Link Register |
  157. // +===========================================+
  158. // 10030 | ........ | ........ | ........ | ........ |
  159. // 10034 | ........ | ........ | ........ | ........ |
  160. // +-------------------------------------------+
  161. // 10038 | ........ | ........ | ........ | ........ |
  162. // 1003c | ........ | ........ | ........ | ........ |
  163. // +-------------------------------------------+
  164. //
  165. // [sp] = 10030 :: >>initial value<<
  166. // sp = 10020 :: stp fp, lr, [sp, #-16]!
  167. // fp = sp == 10020 :: mov fp, sp
  168. // [sp] == 10020 :: stp x28, x27, [sp, #-16]!
  169. // sp == 10010 :: >>final value<<
  170. //
  171. // The frame pointer (w29) points to address 10020. If we use an offset of
  172. // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
  173. // for w27, and -32 for w28:
  174. //
  175. // Ltmp1:
  176. // .cfi_def_cfa w29, 16
  177. // Ltmp2:
  178. // .cfi_offset w30, -8
  179. // Ltmp3:
  180. // .cfi_offset w29, -16
  181. // Ltmp4:
  182. // .cfi_offset w27, -24
  183. // Ltmp5:
  184. // .cfi_offset w28, -32
  185. //
  186. //===----------------------------------------------------------------------===//
  187. #include "AArch64FrameLowering.h"
  188. #include "AArch64InstrInfo.h"
  189. #include "AArch64MachineFunctionInfo.h"
  190. #include "AArch64RegisterInfo.h"
  191. #include "AArch64Subtarget.h"
  192. #include "AArch64TargetMachine.h"
  193. #include "MCTargetDesc/AArch64AddressingModes.h"
  194. #include "MCTargetDesc/AArch64MCTargetDesc.h"
  195. #include "llvm/ADT/ScopeExit.h"
  196. #include "llvm/ADT/SmallVector.h"
  197. #include "llvm/ADT/Statistic.h"
  198. #include "llvm/CodeGen/LivePhysRegs.h"
  199. #include "llvm/CodeGen/MachineBasicBlock.h"
  200. #include "llvm/CodeGen/MachineFrameInfo.h"
  201. #include "llvm/CodeGen/MachineFunction.h"
  202. #include "llvm/CodeGen/MachineInstr.h"
  203. #include "llvm/CodeGen/MachineInstrBuilder.h"
  204. #include "llvm/CodeGen/MachineMemOperand.h"
  205. #include "llvm/CodeGen/MachineModuleInfo.h"
  206. #include "llvm/CodeGen/MachineOperand.h"
  207. #include "llvm/CodeGen/MachineRegisterInfo.h"
  208. #include "llvm/CodeGen/RegisterScavenging.h"
  209. #include "llvm/CodeGen/TargetInstrInfo.h"
  210. #include "llvm/CodeGen/TargetRegisterInfo.h"
  211. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  212. #include "llvm/CodeGen/WinEHFuncInfo.h"
  213. #include "llvm/IR/Attributes.h"
  214. #include "llvm/IR/CallingConv.h"
  215. #include "llvm/IR/DataLayout.h"
  216. #include "llvm/IR/DebugLoc.h"
  217. #include "llvm/IR/Function.h"
  218. #include "llvm/MC/MCAsmInfo.h"
  219. #include "llvm/MC/MCDwarf.h"
  220. #include "llvm/Support/CommandLine.h"
  221. #include "llvm/Support/Debug.h"
  222. #include "llvm/Support/ErrorHandling.h"
  223. #include "llvm/Support/MathExtras.h"
  224. #include "llvm/Support/raw_ostream.h"
  225. #include "llvm/Target/TargetMachine.h"
  226. #include "llvm/Target/TargetOptions.h"
  227. #include <cassert>
  228. #include <cstdint>
  229. #include <iterator>
  230. #include <optional>
  231. #include <vector>
  232. using namespace llvm;
  233. #define DEBUG_TYPE "frame-info"
  234. static cl::opt<bool> EnableRedZone("aarch64-redzone",
  235. cl::desc("enable use of redzone on AArch64"),
  236. cl::init(false), cl::Hidden);
  237. static cl::opt<bool>
  238. ReverseCSRRestoreSeq("reverse-csr-restore-seq",
  239. cl::desc("reverse the CSR restore sequence"),
  240. cl::init(false), cl::Hidden);
  241. static cl::opt<bool> StackTaggingMergeSetTag(
  242. "stack-tagging-merge-settag",
  243. cl::desc("merge settag instruction in function epilog"), cl::init(true),
  244. cl::Hidden);
  245. static cl::opt<bool> OrderFrameObjects("aarch64-order-frame-objects",
  246. cl::desc("sort stack allocations"),
  247. cl::init(true), cl::Hidden);
  248. cl::opt<bool> EnableHomogeneousPrologEpilog(
  249. "homogeneous-prolog-epilog", cl::Hidden,
  250. cl::desc("Emit homogeneous prologue and epilogue for the size "
  251. "optimization (default = off)"));
  252. STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
  253. /// Returns how much of the incoming argument stack area (in bytes) we should
  254. /// clean up in an epilogue. For the C calling convention this will be 0, for
  255. /// guaranteed tail call conventions it can be positive (a normal return or a
  256. /// tail call to a function that uses less stack space for arguments) or
  257. /// negative (for a tail call to a function that needs more stack space than us
  258. /// for arguments).
  259. static int64_t getArgumentStackToRestore(MachineFunction &MF,
  260. MachineBasicBlock &MBB) {
  261. MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
  262. bool IsTailCallReturn = false;
  263. if (MBB.end() != MBBI) {
  264. unsigned RetOpcode = MBBI->getOpcode();
  265. IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
  266. RetOpcode == AArch64::TCRETURNri ||
  267. RetOpcode == AArch64::TCRETURNriBTI;
  268. }
  269. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  270. int64_t ArgumentPopSize = 0;
  271. if (IsTailCallReturn) {
  272. MachineOperand &StackAdjust = MBBI->getOperand(1);
  273. // For a tail-call in a callee-pops-arguments environment, some or all of
  274. // the stack may actually be in use for the call's arguments, this is
  275. // calculated during LowerCall and consumed here...
  276. ArgumentPopSize = StackAdjust.getImm();
  277. } else {
  278. // ... otherwise the amount to pop is *all* of the argument space,
  279. // conveniently stored in the MachineFunctionInfo by
  280. // LowerFormalArguments. This will, of course, be zero for the C calling
  281. // convention.
  282. ArgumentPopSize = AFI->getArgumentStackToRestore();
  283. }
  284. return ArgumentPopSize;
  285. }
  286. static bool produceCompactUnwindFrame(MachineFunction &MF);
  287. static bool needsWinCFI(const MachineFunction &MF);
  288. static StackOffset getSVEStackSize(const MachineFunction &MF);
  289. static bool needsShadowCallStackPrologueEpilogue(MachineFunction &MF);
  290. /// Returns true if a homogeneous prolog or epilog code can be emitted
  291. /// for the size optimization. If possible, a frame helper call is injected.
  292. /// When Exit block is given, this check is for epilog.
  293. bool AArch64FrameLowering::homogeneousPrologEpilog(
  294. MachineFunction &MF, MachineBasicBlock *Exit) const {
  295. if (!MF.getFunction().hasMinSize())
  296. return false;
  297. if (!EnableHomogeneousPrologEpilog)
  298. return false;
  299. if (ReverseCSRRestoreSeq)
  300. return false;
  301. if (EnableRedZone)
  302. return false;
  303. // TODO: Window is supported yet.
  304. if (needsWinCFI(MF))
  305. return false;
  306. // TODO: SVE is not supported yet.
  307. if (getSVEStackSize(MF))
  308. return false;
  309. // Bail on stack adjustment needed on return for simplicity.
  310. const MachineFrameInfo &MFI = MF.getFrameInfo();
  311. const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  312. if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))
  313. return false;
  314. if (Exit && getArgumentStackToRestore(MF, *Exit))
  315. return false;
  316. return true;
  317. }
  318. /// Returns true if CSRs should be paired.
  319. bool AArch64FrameLowering::producePairRegisters(MachineFunction &MF) const {
  320. return produceCompactUnwindFrame(MF) || homogeneousPrologEpilog(MF);
  321. }
  322. /// This is the biggest offset to the stack pointer we can encode in aarch64
  323. /// instructions (without using a separate calculation and a temp register).
  324. /// Note that the exception here are vector stores/loads which cannot encode any
  325. /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
  326. static const unsigned DefaultSafeSPDisplacement = 255;
  327. /// Look at each instruction that references stack frames and return the stack
  328. /// size limit beyond which some of these instructions will require a scratch
  329. /// register during their expansion later.
  330. static unsigned estimateRSStackSizeLimit(MachineFunction &MF) {
  331. // FIXME: For now, just conservatively guestimate based on unscaled indexing
  332. // range. We'll end up allocating an unnecessary spill slot a lot, but
  333. // realistically that's not a big deal at this stage of the game.
  334. for (MachineBasicBlock &MBB : MF) {
  335. for (MachineInstr &MI : MBB) {
  336. if (MI.isDebugInstr() || MI.isPseudo() ||
  337. MI.getOpcode() == AArch64::ADDXri ||
  338. MI.getOpcode() == AArch64::ADDSXri)
  339. continue;
  340. for (const MachineOperand &MO : MI.operands()) {
  341. if (!MO.isFI())
  342. continue;
  343. StackOffset Offset;
  344. if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
  345. AArch64FrameOffsetCannotUpdate)
  346. return 0;
  347. }
  348. }
  349. }
  350. return DefaultSafeSPDisplacement;
  351. }
  352. TargetStackID::Value
  353. AArch64FrameLowering::getStackIDForScalableVectors() const {
  354. return TargetStackID::ScalableVector;
  355. }
  356. /// Returns the size of the fixed object area (allocated next to sp on entry)
  357. /// On Win64 this may include a var args area and an UnwindHelp object for EH.
  358. static unsigned getFixedObjectSize(const MachineFunction &MF,
  359. const AArch64FunctionInfo *AFI, bool IsWin64,
  360. bool IsFunclet) {
  361. if (!IsWin64 || IsFunclet) {
  362. return AFI->getTailCallReservedStack();
  363. } else {
  364. if (AFI->getTailCallReservedStack() != 0)
  365. report_fatal_error("cannot generate ABI-changing tail call for Win64");
  366. // Var args are stored here in the primary function.
  367. const unsigned VarArgsArea = AFI->getVarArgsGPRSize();
  368. // To support EH funclets we allocate an UnwindHelp object
  369. const unsigned UnwindHelpObject = (MF.hasEHFunclets() ? 8 : 0);
  370. return alignTo(VarArgsArea + UnwindHelpObject, 16);
  371. }
  372. }
  373. /// Returns the size of the entire SVE stackframe (calleesaves + spills).
  374. static StackOffset getSVEStackSize(const MachineFunction &MF) {
  375. const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  376. return StackOffset::getScalable((int64_t)AFI->getStackSizeSVE());
  377. }
  378. bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
  379. if (!EnableRedZone)
  380. return false;
  381. // Don't use the red zone if the function explicitly asks us not to.
  382. // This is typically used for kernel code.
  383. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  384. const unsigned RedZoneSize =
  385. Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
  386. if (!RedZoneSize)
  387. return false;
  388. const MachineFrameInfo &MFI = MF.getFrameInfo();
  389. const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  390. uint64_t NumBytes = AFI->getLocalStackSize();
  391. return !(MFI.hasCalls() || hasFP(MF) || NumBytes > RedZoneSize ||
  392. getSVEStackSize(MF));
  393. }
  394. /// hasFP - Return true if the specified function should have a dedicated frame
  395. /// pointer register.
  396. bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
  397. const MachineFrameInfo &MFI = MF.getFrameInfo();
  398. const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  399. // Win64 EH requires a frame pointer if funclets are present, as the locals
  400. // are accessed off the frame pointer in both the parent function and the
  401. // funclets.
  402. if (MF.hasEHFunclets())
  403. return true;
  404. // Retain behavior of always omitting the FP for leaf functions when possible.
  405. if (MF.getTarget().Options.DisableFramePointerElim(MF))
  406. return true;
  407. if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
  408. MFI.hasStackMap() || MFI.hasPatchPoint() ||
  409. RegInfo->hasStackRealignment(MF))
  410. return true;
  411. // With large callframes around we may need to use FP to access the scavenging
  412. // emergency spillslot.
  413. //
  414. // Unfortunately some calls to hasFP() like machine verifier ->
  415. // getReservedReg() -> hasFP in the middle of global isel are too early
  416. // to know the max call frame size. Hopefully conservatively returning "true"
  417. // in those cases is fine.
  418. // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
  419. if (!MFI.isMaxCallFrameSizeComputed() ||
  420. MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement)
  421. return true;
  422. return false;
  423. }
  424. /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
  425. /// not required, we reserve argument space for call sites in the function
  426. /// immediately on entry to the current function. This eliminates the need for
  427. /// add/sub sp brackets around call sites. Returns true if the call frame is
  428. /// included as part of the stack frame.
  429. bool
  430. AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
  431. return !MF.getFrameInfo().hasVarSizedObjects();
  432. }
  433. MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr(
  434. MachineFunction &MF, MachineBasicBlock &MBB,
  435. MachineBasicBlock::iterator I) const {
  436. const AArch64InstrInfo *TII =
  437. static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
  438. DebugLoc DL = I->getDebugLoc();
  439. unsigned Opc = I->getOpcode();
  440. bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
  441. uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
  442. if (!hasReservedCallFrame(MF)) {
  443. int64_t Amount = I->getOperand(0).getImm();
  444. Amount = alignTo(Amount, getStackAlign());
  445. if (!IsDestroy)
  446. Amount = -Amount;
  447. // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
  448. // doesn't have to pop anything), then the first operand will be zero too so
  449. // this adjustment is a no-op.
  450. if (CalleePopAmount == 0) {
  451. // FIXME: in-function stack adjustment for calls is limited to 24-bits
  452. // because there's no guaranteed temporary register available.
  453. //
  454. // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
  455. // 1) For offset <= 12-bit, we use LSL #0
  456. // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
  457. // LSL #0, and the other uses LSL #12.
  458. //
  459. // Most call frames will be allocated at the start of a function so
  460. // this is OK, but it is a limitation that needs dealing with.
  461. assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
  462. emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
  463. StackOffset::getFixed(Amount), TII);
  464. }
  465. } else if (CalleePopAmount != 0) {
  466. // If the calling convention demands that the callee pops arguments from the
  467. // stack, we want to add it back if we have a reserved call frame.
  468. assert(CalleePopAmount < 0xffffff && "call frame too large");
  469. emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
  470. StackOffset::getFixed(-(int64_t)CalleePopAmount), TII);
  471. }
  472. return MBB.erase(I);
  473. }
  474. void AArch64FrameLowering::emitCalleeSavedGPRLocations(
  475. MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
  476. MachineFunction &MF = *MBB.getParent();
  477. MachineFrameInfo &MFI = MF.getFrameInfo();
  478. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  479. if (CSI.empty())
  480. return;
  481. const TargetSubtargetInfo &STI = MF.getSubtarget();
  482. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  483. const TargetInstrInfo &TII = *STI.getInstrInfo();
  484. DebugLoc DL = MBB.findDebugLoc(MBBI);
  485. for (const auto &Info : CSI) {
  486. if (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector)
  487. continue;
  488. assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
  489. unsigned DwarfReg = TRI.getDwarfRegNum(Info.getReg(), true);
  490. int64_t Offset =
  491. MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea();
  492. unsigned CFIIndex = MF.addFrameInst(
  493. MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
  494. BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  495. .addCFIIndex(CFIIndex)
  496. .setMIFlags(MachineInstr::FrameSetup);
  497. }
  498. }
  499. void AArch64FrameLowering::emitCalleeSavedSVELocations(
  500. MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
  501. MachineFunction &MF = *MBB.getParent();
  502. MachineFrameInfo &MFI = MF.getFrameInfo();
  503. // Add callee saved registers to move list.
  504. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  505. if (CSI.empty())
  506. return;
  507. const TargetSubtargetInfo &STI = MF.getSubtarget();
  508. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  509. const TargetInstrInfo &TII = *STI.getInstrInfo();
  510. DebugLoc DL = MBB.findDebugLoc(MBBI);
  511. AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
  512. for (const auto &Info : CSI) {
  513. if (!(MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
  514. continue;
  515. // Not all unwinders may know about SVE registers, so assume the lowest
  516. // common demoninator.
  517. assert(!Info.isSpilledToReg() && "Spilling to registers not implemented");
  518. unsigned Reg = Info.getReg();
  519. if (!static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
  520. continue;
  521. StackOffset Offset =
  522. StackOffset::getScalable(MFI.getObjectOffset(Info.getFrameIdx())) -
  523. StackOffset::getFixed(AFI.getCalleeSavedStackSize(MFI));
  524. unsigned CFIIndex = MF.addFrameInst(createCFAOffset(TRI, Reg, Offset));
  525. BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  526. .addCFIIndex(CFIIndex)
  527. .setMIFlags(MachineInstr::FrameSetup);
  528. }
  529. }
  530. static void insertCFISameValue(const MCInstrDesc &Desc, MachineFunction &MF,
  531. MachineBasicBlock &MBB,
  532. MachineBasicBlock::iterator InsertPt,
  533. unsigned DwarfReg) {
  534. unsigned CFIIndex =
  535. MF.addFrameInst(MCCFIInstruction::createSameValue(nullptr, DwarfReg));
  536. BuildMI(MBB, InsertPt, DebugLoc(), Desc).addCFIIndex(CFIIndex);
  537. }
  538. void AArch64FrameLowering::resetCFIToInitialState(
  539. MachineBasicBlock &MBB) const {
  540. MachineFunction &MF = *MBB.getParent();
  541. const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  542. const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
  543. const auto &TRI =
  544. static_cast<const AArch64RegisterInfo &>(*Subtarget.getRegisterInfo());
  545. const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
  546. const MCInstrDesc &CFIDesc = TII.get(TargetOpcode::CFI_INSTRUCTION);
  547. DebugLoc DL;
  548. // Reset the CFA to `SP + 0`.
  549. MachineBasicBlock::iterator InsertPt = MBB.begin();
  550. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
  551. nullptr, TRI.getDwarfRegNum(AArch64::SP, true), 0));
  552. BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
  553. // Flip the RA sign state.
  554. if (MFI.shouldSignReturnAddress(MF)) {
  555. CFIIndex = MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
  556. BuildMI(MBB, InsertPt, DL, CFIDesc).addCFIIndex(CFIIndex);
  557. }
  558. // Shadow call stack uses X18, reset it.
  559. if (needsShadowCallStackPrologueEpilogue(MF))
  560. insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
  561. TRI.getDwarfRegNum(AArch64::X18, true));
  562. // Emit .cfi_same_value for callee-saved registers.
  563. const std::vector<CalleeSavedInfo> &CSI =
  564. MF.getFrameInfo().getCalleeSavedInfo();
  565. for (const auto &Info : CSI) {
  566. unsigned Reg = Info.getReg();
  567. if (!TRI.regNeedsCFI(Reg, Reg))
  568. continue;
  569. insertCFISameValue(CFIDesc, MF, MBB, InsertPt,
  570. TRI.getDwarfRegNum(Reg, true));
  571. }
  572. }
  573. static void emitCalleeSavedRestores(MachineBasicBlock &MBB,
  574. MachineBasicBlock::iterator MBBI,
  575. bool SVE) {
  576. MachineFunction &MF = *MBB.getParent();
  577. MachineFrameInfo &MFI = MF.getFrameInfo();
  578. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  579. if (CSI.empty())
  580. return;
  581. const TargetSubtargetInfo &STI = MF.getSubtarget();
  582. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  583. const TargetInstrInfo &TII = *STI.getInstrInfo();
  584. DebugLoc DL = MBB.findDebugLoc(MBBI);
  585. for (const auto &Info : CSI) {
  586. if (SVE !=
  587. (MFI.getStackID(Info.getFrameIdx()) == TargetStackID::ScalableVector))
  588. continue;
  589. unsigned Reg = Info.getReg();
  590. if (SVE &&
  591. !static_cast<const AArch64RegisterInfo &>(TRI).regNeedsCFI(Reg, Reg))
  592. continue;
  593. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createRestore(
  594. nullptr, TRI.getDwarfRegNum(Info.getReg(), true)));
  595. BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  596. .addCFIIndex(CFIIndex)
  597. .setMIFlags(MachineInstr::FrameDestroy);
  598. }
  599. }
  600. void AArch64FrameLowering::emitCalleeSavedGPRRestores(
  601. MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
  602. emitCalleeSavedRestores(MBB, MBBI, false);
  603. }
  604. void AArch64FrameLowering::emitCalleeSavedSVERestores(
  605. MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
  606. emitCalleeSavedRestores(MBB, MBBI, true);
  607. }
  608. static MCRegister getRegisterOrZero(MCRegister Reg, bool HasSVE) {
  609. switch (Reg.id()) {
  610. default:
  611. // The called routine is expected to preserve r19-r28
  612. // r29 and r30 are used as frame pointer and link register resp.
  613. return 0;
  614. // GPRs
  615. #define CASE(n) \
  616. case AArch64::W##n: \
  617. case AArch64::X##n: \
  618. return AArch64::X##n
  619. CASE(0);
  620. CASE(1);
  621. CASE(2);
  622. CASE(3);
  623. CASE(4);
  624. CASE(5);
  625. CASE(6);
  626. CASE(7);
  627. CASE(8);
  628. CASE(9);
  629. CASE(10);
  630. CASE(11);
  631. CASE(12);
  632. CASE(13);
  633. CASE(14);
  634. CASE(15);
  635. CASE(16);
  636. CASE(17);
  637. CASE(18);
  638. #undef CASE
  639. // FPRs
  640. #define CASE(n) \
  641. case AArch64::B##n: \
  642. case AArch64::H##n: \
  643. case AArch64::S##n: \
  644. case AArch64::D##n: \
  645. case AArch64::Q##n: \
  646. return HasSVE ? AArch64::Z##n : AArch64::Q##n
  647. CASE(0);
  648. CASE(1);
  649. CASE(2);
  650. CASE(3);
  651. CASE(4);
  652. CASE(5);
  653. CASE(6);
  654. CASE(7);
  655. CASE(8);
  656. CASE(9);
  657. CASE(10);
  658. CASE(11);
  659. CASE(12);
  660. CASE(13);
  661. CASE(14);
  662. CASE(15);
  663. CASE(16);
  664. CASE(17);
  665. CASE(18);
  666. CASE(19);
  667. CASE(20);
  668. CASE(21);
  669. CASE(22);
  670. CASE(23);
  671. CASE(24);
  672. CASE(25);
  673. CASE(26);
  674. CASE(27);
  675. CASE(28);
  676. CASE(29);
  677. CASE(30);
  678. CASE(31);
  679. #undef CASE
  680. }
  681. }
  682. void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
  683. MachineBasicBlock &MBB) const {
  684. // Insertion point.
  685. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  686. // Fake a debug loc.
  687. DebugLoc DL;
  688. if (MBBI != MBB.end())
  689. DL = MBBI->getDebugLoc();
  690. const MachineFunction &MF = *MBB.getParent();
  691. const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
  692. const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
  693. BitVector GPRsToZero(TRI.getNumRegs());
  694. BitVector FPRsToZero(TRI.getNumRegs());
  695. bool HasSVE = STI.hasSVE();
  696. for (MCRegister Reg : RegsToZero.set_bits()) {
  697. if (TRI.isGeneralPurposeRegister(MF, Reg)) {
  698. // For GPRs, we only care to clear out the 64-bit register.
  699. if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
  700. GPRsToZero.set(XReg);
  701. } else if (AArch64::FPR128RegClass.contains(Reg) ||
  702. AArch64::FPR64RegClass.contains(Reg) ||
  703. AArch64::FPR32RegClass.contains(Reg) ||
  704. AArch64::FPR16RegClass.contains(Reg) ||
  705. AArch64::FPR8RegClass.contains(Reg)) {
  706. // For FPRs,
  707. if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
  708. FPRsToZero.set(XReg);
  709. }
  710. }
  711. const AArch64InstrInfo &TII = *STI.getInstrInfo();
  712. // Zero out GPRs.
  713. for (MCRegister Reg : GPRsToZero.set_bits())
  714. BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), Reg).addImm(0);
  715. // Zero out FP/vector registers.
  716. for (MCRegister Reg : FPRsToZero.set_bits())
  717. if (HasSVE)
  718. BuildMI(MBB, MBBI, DL, TII.get(AArch64::DUP_ZI_D), Reg)
  719. .addImm(0)
  720. .addImm(0);
  721. else
  722. BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVIv2d_ns), Reg).addImm(0);
  723. if (HasSVE) {
  724. for (MCRegister PReg :
  725. {AArch64::P0, AArch64::P1, AArch64::P2, AArch64::P3, AArch64::P4,
  726. AArch64::P5, AArch64::P6, AArch64::P7, AArch64::P8, AArch64::P9,
  727. AArch64::P10, AArch64::P11, AArch64::P12, AArch64::P13, AArch64::P14,
  728. AArch64::P15}) {
  729. if (RegsToZero[PReg])
  730. BuildMI(MBB, MBBI, DL, TII.get(AArch64::PFALSE), PReg);
  731. }
  732. }
  733. }
  734. // Find a scratch register that we can use at the start of the prologue to
  735. // re-align the stack pointer. We avoid using callee-save registers since they
  736. // may appear to be free when this is called from canUseAsPrologue (during
  737. // shrink wrapping), but then no longer be free when this is called from
  738. // emitPrologue.
  739. //
  740. // FIXME: This is a bit conservative, since in the above case we could use one
  741. // of the callee-save registers as a scratch temp to re-align the stack pointer,
  742. // but we would then have to make sure that we were in fact saving at least one
  743. // callee-save register in the prologue, which is additional complexity that
  744. // doesn't seem worth the benefit.
  745. static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) {
  746. MachineFunction *MF = MBB->getParent();
  747. // If MBB is an entry block, use X9 as the scratch register
  748. if (&MF->front() == MBB)
  749. return AArch64::X9;
  750. const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
  751. const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
  752. LivePhysRegs LiveRegs(TRI);
  753. LiveRegs.addLiveIns(*MBB);
  754. // Mark callee saved registers as used so we will not choose them.
  755. const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
  756. for (unsigned i = 0; CSRegs[i]; ++i)
  757. LiveRegs.addReg(CSRegs[i]);
  758. // Prefer X9 since it was historically used for the prologue scratch reg.
  759. const MachineRegisterInfo &MRI = MF->getRegInfo();
  760. if (LiveRegs.available(MRI, AArch64::X9))
  761. return AArch64::X9;
  762. for (unsigned Reg : AArch64::GPR64RegClass) {
  763. if (LiveRegs.available(MRI, Reg))
  764. return Reg;
  765. }
  766. return AArch64::NoRegister;
  767. }
  768. bool AArch64FrameLowering::canUseAsPrologue(
  769. const MachineBasicBlock &MBB) const {
  770. const MachineFunction *MF = MBB.getParent();
  771. MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
  772. const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
  773. const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  774. // Don't need a scratch register if we're not going to re-align the stack.
  775. if (!RegInfo->hasStackRealignment(*MF))
  776. return true;
  777. // Otherwise, we can use any block as long as it has a scratch register
  778. // available.
  779. return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister;
  780. }
  781. static bool windowsRequiresStackProbe(MachineFunction &MF,
  782. uint64_t StackSizeInBytes) {
  783. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  784. if (!Subtarget.isTargetWindows())
  785. return false;
  786. const Function &F = MF.getFunction();
  787. // TODO: When implementing stack protectors, take that into account
  788. // for the probe threshold.
  789. unsigned StackProbeSize =
  790. F.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
  791. return (StackSizeInBytes >= StackProbeSize) &&
  792. !F.hasFnAttribute("no-stack-arg-probe");
  793. }
  794. static bool needsWinCFI(const MachineFunction &MF) {
  795. const Function &F = MF.getFunction();
  796. return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
  797. F.needsUnwindTableEntry();
  798. }
  799. bool AArch64FrameLowering::shouldCombineCSRLocalStackBump(
  800. MachineFunction &MF, uint64_t StackBumpBytes) const {
  801. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  802. const MachineFrameInfo &MFI = MF.getFrameInfo();
  803. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  804. const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  805. if (homogeneousPrologEpilog(MF))
  806. return false;
  807. if (AFI->getLocalStackSize() == 0)
  808. return false;
  809. // For WinCFI, if optimizing for size, prefer to not combine the stack bump
  810. // (to force a stp with predecrement) to match the packed unwind format,
  811. // provided that there actually are any callee saved registers to merge the
  812. // decrement with.
  813. // This is potentially marginally slower, but allows using the packed
  814. // unwind format for functions that both have a local area and callee saved
  815. // registers. Using the packed unwind format notably reduces the size of
  816. // the unwind info.
  817. if (needsWinCFI(MF) && AFI->getCalleeSavedStackSize() > 0 &&
  818. MF.getFunction().hasOptSize())
  819. return false;
  820. // 512 is the maximum immediate for stp/ldp that will be used for
  821. // callee-save save/restores
  822. if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes))
  823. return false;
  824. if (MFI.hasVarSizedObjects())
  825. return false;
  826. if (RegInfo->hasStackRealignment(MF))
  827. return false;
  828. // This isn't strictly necessary, but it simplifies things a bit since the
  829. // current RedZone handling code assumes the SP is adjusted by the
  830. // callee-save save/restore code.
  831. if (canUseRedZone(MF))
  832. return false;
  833. // When there is an SVE area on the stack, always allocate the
  834. // callee-saves and spills/locals separately.
  835. if (getSVEStackSize(MF))
  836. return false;
  837. return true;
  838. }
  839. bool AArch64FrameLowering::shouldCombineCSRLocalStackBumpInEpilogue(
  840. MachineBasicBlock &MBB, unsigned StackBumpBytes) const {
  841. if (!shouldCombineCSRLocalStackBump(*MBB.getParent(), StackBumpBytes))
  842. return false;
  843. if (MBB.empty())
  844. return true;
  845. // Disable combined SP bump if the last instruction is an MTE tag store. It
  846. // is almost always better to merge SP adjustment into those instructions.
  847. MachineBasicBlock::iterator LastI = MBB.getFirstTerminator();
  848. MachineBasicBlock::iterator Begin = MBB.begin();
  849. while (LastI != Begin) {
  850. --LastI;
  851. if (LastI->isTransient())
  852. continue;
  853. if (!LastI->getFlag(MachineInstr::FrameDestroy))
  854. break;
  855. }
  856. switch (LastI->getOpcode()) {
  857. case AArch64::STGloop:
  858. case AArch64::STZGloop:
  859. case AArch64::STGOffset:
  860. case AArch64::STZGOffset:
  861. case AArch64::ST2GOffset:
  862. case AArch64::STZ2GOffset:
  863. return false;
  864. default:
  865. return true;
  866. }
  867. llvm_unreachable("unreachable");
  868. }
  869. // Given a load or a store instruction, generate an appropriate unwinding SEH
  870. // code on Windows.
  871. static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI,
  872. const TargetInstrInfo &TII,
  873. MachineInstr::MIFlag Flag) {
  874. unsigned Opc = MBBI->getOpcode();
  875. MachineBasicBlock *MBB = MBBI->getParent();
  876. MachineFunction &MF = *MBB->getParent();
  877. DebugLoc DL = MBBI->getDebugLoc();
  878. unsigned ImmIdx = MBBI->getNumOperands() - 1;
  879. int Imm = MBBI->getOperand(ImmIdx).getImm();
  880. MachineInstrBuilder MIB;
  881. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  882. const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  883. switch (Opc) {
  884. default:
  885. llvm_unreachable("No SEH Opcode for this instruction");
  886. case AArch64::LDPDpost:
  887. Imm = -Imm;
  888. [[fallthrough]];
  889. case AArch64::STPDpre: {
  890. unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
  891. unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
  892. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
  893. .addImm(Reg0)
  894. .addImm(Reg1)
  895. .addImm(Imm * 8)
  896. .setMIFlag(Flag);
  897. break;
  898. }
  899. case AArch64::LDPXpost:
  900. Imm = -Imm;
  901. [[fallthrough]];
  902. case AArch64::STPXpre: {
  903. Register Reg0 = MBBI->getOperand(1).getReg();
  904. Register Reg1 = MBBI->getOperand(2).getReg();
  905. if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
  906. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
  907. .addImm(Imm * 8)
  908. .setMIFlag(Flag);
  909. else
  910. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
  911. .addImm(RegInfo->getSEHRegNum(Reg0))
  912. .addImm(RegInfo->getSEHRegNum(Reg1))
  913. .addImm(Imm * 8)
  914. .setMIFlag(Flag);
  915. break;
  916. }
  917. case AArch64::LDRDpost:
  918. Imm = -Imm;
  919. [[fallthrough]];
  920. case AArch64::STRDpre: {
  921. unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
  922. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
  923. .addImm(Reg)
  924. .addImm(Imm)
  925. .setMIFlag(Flag);
  926. break;
  927. }
  928. case AArch64::LDRXpost:
  929. Imm = -Imm;
  930. [[fallthrough]];
  931. case AArch64::STRXpre: {
  932. unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
  933. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
  934. .addImm(Reg)
  935. .addImm(Imm)
  936. .setMIFlag(Flag);
  937. break;
  938. }
  939. case AArch64::STPDi:
  940. case AArch64::LDPDi: {
  941. unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
  942. unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
  943. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
  944. .addImm(Reg0)
  945. .addImm(Reg1)
  946. .addImm(Imm * 8)
  947. .setMIFlag(Flag);
  948. break;
  949. }
  950. case AArch64::STPXi:
  951. case AArch64::LDPXi: {
  952. Register Reg0 = MBBI->getOperand(0).getReg();
  953. Register Reg1 = MBBI->getOperand(1).getReg();
  954. if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
  955. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
  956. .addImm(Imm * 8)
  957. .setMIFlag(Flag);
  958. else
  959. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
  960. .addImm(RegInfo->getSEHRegNum(Reg0))
  961. .addImm(RegInfo->getSEHRegNum(Reg1))
  962. .addImm(Imm * 8)
  963. .setMIFlag(Flag);
  964. break;
  965. }
  966. case AArch64::STRXui:
  967. case AArch64::LDRXui: {
  968. int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
  969. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
  970. .addImm(Reg)
  971. .addImm(Imm * 8)
  972. .setMIFlag(Flag);
  973. break;
  974. }
  975. case AArch64::STRDui:
  976. case AArch64::LDRDui: {
  977. unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
  978. MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
  979. .addImm(Reg)
  980. .addImm(Imm * 8)
  981. .setMIFlag(Flag);
  982. break;
  983. }
  984. }
  985. auto I = MBB->insertAfter(MBBI, MIB);
  986. return I;
  987. }
  988. // Fix up the SEH opcode associated with the save/restore instruction.
  989. static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI,
  990. unsigned LocalStackSize) {
  991. MachineOperand *ImmOpnd = nullptr;
  992. unsigned ImmIdx = MBBI->getNumOperands() - 1;
  993. switch (MBBI->getOpcode()) {
  994. default:
  995. llvm_unreachable("Fix the offset in the SEH instruction");
  996. case AArch64::SEH_SaveFPLR:
  997. case AArch64::SEH_SaveRegP:
  998. case AArch64::SEH_SaveReg:
  999. case AArch64::SEH_SaveFRegP:
  1000. case AArch64::SEH_SaveFReg:
  1001. ImmOpnd = &MBBI->getOperand(ImmIdx);
  1002. break;
  1003. }
  1004. if (ImmOpnd)
  1005. ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize);
  1006. }
  1007. // Convert callee-save register save/restore instruction to do stack pointer
  1008. // decrement/increment to allocate/deallocate the callee-save stack area by
  1009. // converting store/load to use pre/post increment version.
  1010. static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec(
  1011. MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
  1012. const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc,
  1013. bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFI,
  1014. MachineInstr::MIFlag FrameFlag = MachineInstr::FrameSetup,
  1015. int CFAOffset = 0) {
  1016. unsigned NewOpc;
  1017. switch (MBBI->getOpcode()) {
  1018. default:
  1019. llvm_unreachable("Unexpected callee-save save/restore opcode!");
  1020. case AArch64::STPXi:
  1021. NewOpc = AArch64::STPXpre;
  1022. break;
  1023. case AArch64::STPDi:
  1024. NewOpc = AArch64::STPDpre;
  1025. break;
  1026. case AArch64::STPQi:
  1027. NewOpc = AArch64::STPQpre;
  1028. break;
  1029. case AArch64::STRXui:
  1030. NewOpc = AArch64::STRXpre;
  1031. break;
  1032. case AArch64::STRDui:
  1033. NewOpc = AArch64::STRDpre;
  1034. break;
  1035. case AArch64::STRQui:
  1036. NewOpc = AArch64::STRQpre;
  1037. break;
  1038. case AArch64::LDPXi:
  1039. NewOpc = AArch64::LDPXpost;
  1040. break;
  1041. case AArch64::LDPDi:
  1042. NewOpc = AArch64::LDPDpost;
  1043. break;
  1044. case AArch64::LDPQi:
  1045. NewOpc = AArch64::LDPQpost;
  1046. break;
  1047. case AArch64::LDRXui:
  1048. NewOpc = AArch64::LDRXpost;
  1049. break;
  1050. case AArch64::LDRDui:
  1051. NewOpc = AArch64::LDRDpost;
  1052. break;
  1053. case AArch64::LDRQui:
  1054. NewOpc = AArch64::LDRQpost;
  1055. break;
  1056. }
  1057. // Get rid of the SEH code associated with the old instruction.
  1058. if (NeedsWinCFI) {
  1059. auto SEH = std::next(MBBI);
  1060. if (AArch64InstrInfo::isSEHInstruction(*SEH))
  1061. SEH->eraseFromParent();
  1062. }
  1063. TypeSize Scale = TypeSize::Fixed(1);
  1064. unsigned Width;
  1065. int64_t MinOffset, MaxOffset;
  1066. bool Success = static_cast<const AArch64InstrInfo *>(TII)->getMemOpInfo(
  1067. NewOpc, Scale, Width, MinOffset, MaxOffset);
  1068. (void)Success;
  1069. assert(Success && "unknown load/store opcode");
  1070. // If the first store isn't right where we want SP then we can't fold the
  1071. // update in so create a normal arithmetic instruction instead.
  1072. MachineFunction &MF = *MBB.getParent();
  1073. if (MBBI->getOperand(MBBI->getNumOperands() - 1).getImm() != 0 ||
  1074. CSStackSizeInc < MinOffset || CSStackSizeInc > MaxOffset) {
  1075. emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
  1076. StackOffset::getFixed(CSStackSizeInc), TII, FrameFlag,
  1077. false, false, nullptr, EmitCFI,
  1078. StackOffset::getFixed(CFAOffset));
  1079. return std::prev(MBBI);
  1080. }
  1081. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
  1082. MIB.addReg(AArch64::SP, RegState::Define);
  1083. // Copy all operands other than the immediate offset.
  1084. unsigned OpndIdx = 0;
  1085. for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd;
  1086. ++OpndIdx)
  1087. MIB.add(MBBI->getOperand(OpndIdx));
  1088. assert(MBBI->getOperand(OpndIdx).getImm() == 0 &&
  1089. "Unexpected immediate offset in first/last callee-save save/restore "
  1090. "instruction!");
  1091. assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP &&
  1092. "Unexpected base register in callee-save save/restore instruction!");
  1093. assert(CSStackSizeInc % Scale == 0);
  1094. MIB.addImm(CSStackSizeInc / (int)Scale);
  1095. MIB.setMIFlags(MBBI->getFlags());
  1096. MIB.setMemRefs(MBBI->memoperands());
  1097. // Generate a new SEH code that corresponds to the new instruction.
  1098. if (NeedsWinCFI) {
  1099. *HasWinCFI = true;
  1100. InsertSEH(*MIB, *TII, FrameFlag);
  1101. }
  1102. if (EmitCFI) {
  1103. unsigned CFIIndex = MF.addFrameInst(
  1104. MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset - CSStackSizeInc));
  1105. BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  1106. .addCFIIndex(CFIIndex)
  1107. .setMIFlags(FrameFlag);
  1108. }
  1109. return std::prev(MBB.erase(MBBI));
  1110. }
  1111. // Fixup callee-save register save/restore instructions to take into account
  1112. // combined SP bump by adding the local stack size to the stack offsets.
  1113. static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI,
  1114. uint64_t LocalStackSize,
  1115. bool NeedsWinCFI,
  1116. bool *HasWinCFI) {
  1117. if (AArch64InstrInfo::isSEHInstruction(MI))
  1118. return;
  1119. unsigned Opc = MI.getOpcode();
  1120. unsigned Scale;
  1121. switch (Opc) {
  1122. case AArch64::STPXi:
  1123. case AArch64::STRXui:
  1124. case AArch64::STPDi:
  1125. case AArch64::STRDui:
  1126. case AArch64::LDPXi:
  1127. case AArch64::LDRXui:
  1128. case AArch64::LDPDi:
  1129. case AArch64::LDRDui:
  1130. Scale = 8;
  1131. break;
  1132. case AArch64::STPQi:
  1133. case AArch64::STRQui:
  1134. case AArch64::LDPQi:
  1135. case AArch64::LDRQui:
  1136. Scale = 16;
  1137. break;
  1138. default:
  1139. llvm_unreachable("Unexpected callee-save save/restore opcode!");
  1140. }
  1141. unsigned OffsetIdx = MI.getNumExplicitOperands() - 1;
  1142. assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP &&
  1143. "Unexpected base register in callee-save save/restore instruction!");
  1144. // Last operand is immediate offset that needs fixing.
  1145. MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx);
  1146. // All generated opcodes have scaled offsets.
  1147. assert(LocalStackSize % Scale == 0);
  1148. OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale);
  1149. if (NeedsWinCFI) {
  1150. *HasWinCFI = true;
  1151. auto MBBI = std::next(MachineBasicBlock::iterator(MI));
  1152. assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction");
  1153. assert(AArch64InstrInfo::isSEHInstruction(*MBBI) &&
  1154. "Expecting a SEH instruction");
  1155. fixupSEHOpcode(MBBI, LocalStackSize);
  1156. }
  1157. }
  1158. static bool isTargetWindows(const MachineFunction &MF) {
  1159. return MF.getSubtarget<AArch64Subtarget>().isTargetWindows();
  1160. }
  1161. // Convenience function to determine whether I is an SVE callee save.
  1162. static bool IsSVECalleeSave(MachineBasicBlock::iterator I) {
  1163. switch (I->getOpcode()) {
  1164. default:
  1165. return false;
  1166. case AArch64::STR_ZXI:
  1167. case AArch64::STR_PXI:
  1168. case AArch64::LDR_ZXI:
  1169. case AArch64::LDR_PXI:
  1170. return I->getFlag(MachineInstr::FrameSetup) ||
  1171. I->getFlag(MachineInstr::FrameDestroy);
  1172. }
  1173. }
  1174. static bool needsShadowCallStackPrologueEpilogue(MachineFunction &MF) {
  1175. if (!(llvm::any_of(
  1176. MF.getFrameInfo().getCalleeSavedInfo(),
  1177. [](const auto &Info) { return Info.getReg() == AArch64::LR; }) &&
  1178. MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)))
  1179. return false;
  1180. if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18))
  1181. report_fatal_error("Must reserve x18 to use shadow call stack");
  1182. return true;
  1183. }
  1184. static void emitShadowCallStackPrologue(const TargetInstrInfo &TII,
  1185. MachineFunction &MF,
  1186. MachineBasicBlock &MBB,
  1187. MachineBasicBlock::iterator MBBI,
  1188. const DebugLoc &DL, bool NeedsWinCFI,
  1189. bool NeedsUnwindInfo) {
  1190. // Shadow call stack prolog: str x30, [x18], #8
  1191. BuildMI(MBB, MBBI, DL, TII.get(AArch64::STRXpost))
  1192. .addReg(AArch64::X18, RegState::Define)
  1193. .addReg(AArch64::LR)
  1194. .addReg(AArch64::X18)
  1195. .addImm(8)
  1196. .setMIFlag(MachineInstr::FrameSetup);
  1197. // This instruction also makes x18 live-in to the entry block.
  1198. MBB.addLiveIn(AArch64::X18);
  1199. if (NeedsWinCFI)
  1200. BuildMI(MBB, MBBI, DL, TII.get(AArch64::SEH_Nop))
  1201. .setMIFlag(MachineInstr::FrameSetup);
  1202. if (NeedsUnwindInfo) {
  1203. // Emit a CFI instruction that causes 8 to be subtracted from the value of
  1204. // x18 when unwinding past this frame.
  1205. static const char CFIInst[] = {
  1206. dwarf::DW_CFA_val_expression,
  1207. 18, // register
  1208. 2, // length
  1209. static_cast<char>(unsigned(dwarf::DW_OP_breg18)),
  1210. static_cast<char>(-8) & 0x7f, // addend (sleb128)
  1211. };
  1212. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createEscape(
  1213. nullptr, StringRef(CFIInst, sizeof(CFIInst))));
  1214. BuildMI(MBB, MBBI, DL, TII.get(AArch64::CFI_INSTRUCTION))
  1215. .addCFIIndex(CFIIndex)
  1216. .setMIFlag(MachineInstr::FrameSetup);
  1217. }
  1218. }
  1219. static void emitShadowCallStackEpilogue(const TargetInstrInfo &TII,
  1220. MachineFunction &MF,
  1221. MachineBasicBlock &MBB,
  1222. MachineBasicBlock::iterator MBBI,
  1223. const DebugLoc &DL) {
  1224. // Shadow call stack epilog: ldr x30, [x18, #-8]!
  1225. BuildMI(MBB, MBBI, DL, TII.get(AArch64::LDRXpre))
  1226. .addReg(AArch64::X18, RegState::Define)
  1227. .addReg(AArch64::LR, RegState::Define)
  1228. .addReg(AArch64::X18)
  1229. .addImm(-8)
  1230. .setMIFlag(MachineInstr::FrameDestroy);
  1231. if (MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF)) {
  1232. unsigned CFIIndex =
  1233. MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, 18));
  1234. BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1235. .addCFIIndex(CFIIndex)
  1236. .setMIFlags(MachineInstr::FrameDestroy);
  1237. }
  1238. }
  1239. void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
  1240. MachineBasicBlock &MBB) const {
  1241. MachineBasicBlock::iterator MBBI = MBB.begin();
  1242. const MachineFrameInfo &MFI = MF.getFrameInfo();
  1243. const Function &F = MF.getFunction();
  1244. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  1245. const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  1246. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  1247. MachineModuleInfo &MMI = MF.getMMI();
  1248. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  1249. bool EmitCFI = AFI->needsDwarfUnwindInfo(MF);
  1250. bool HasFP = hasFP(MF);
  1251. bool NeedsWinCFI = needsWinCFI(MF);
  1252. bool HasWinCFI = false;
  1253. auto Cleanup = make_scope_exit([&]() { MF.setHasWinCFI(HasWinCFI); });
  1254. bool IsFunclet = MBB.isEHFuncletEntry();
  1255. // At this point, we're going to decide whether or not the function uses a
  1256. // redzone. In most cases, the function doesn't have a redzone so let's
  1257. // assume that's false and set it to true in the case that there's a redzone.
  1258. AFI->setHasRedZone(false);
  1259. // Debug location must be unknown since the first debug location is used
  1260. // to determine the end of the prologue.
  1261. DebugLoc DL;
  1262. const auto &MFnI = *MF.getInfo<AArch64FunctionInfo>();
  1263. if (needsShadowCallStackPrologueEpilogue(MF))
  1264. emitShadowCallStackPrologue(*TII, MF, MBB, MBBI, DL, NeedsWinCFI,
  1265. MFnI.needsDwarfUnwindInfo(MF));
  1266. if (MFnI.shouldSignReturnAddress(MF)) {
  1267. if (MFnI.shouldSignWithBKey()) {
  1268. BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY))
  1269. .setMIFlag(MachineInstr::FrameSetup);
  1270. }
  1271. // No SEH opcode for this one; it doesn't materialize into an
  1272. // instruction on Windows.
  1273. BuildMI(MBB, MBBI, DL,
  1274. TII->get(MFnI.shouldSignWithBKey() ? AArch64::PACIBSP
  1275. : AArch64::PACIASP))
  1276. .setMIFlag(MachineInstr::FrameSetup);
  1277. if (EmitCFI) {
  1278. unsigned CFIIndex =
  1279. MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
  1280. BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  1281. .addCFIIndex(CFIIndex)
  1282. .setMIFlags(MachineInstr::FrameSetup);
  1283. } else if (NeedsWinCFI) {
  1284. HasWinCFI = true;
  1285. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
  1286. .setMIFlag(MachineInstr::FrameSetup);
  1287. }
  1288. }
  1289. if (EmitCFI && MFnI.isMTETagged()) {
  1290. BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITMTETAGGED))
  1291. .setMIFlag(MachineInstr::FrameSetup);
  1292. }
  1293. // We signal the presence of a Swift extended frame to external tools by
  1294. // storing FP with 0b0001 in bits 63:60. In normal userland operation a simple
  1295. // ORR is sufficient, it is assumed a Swift kernel would initialize the TBI
  1296. // bits so that is still true.
  1297. if (HasFP && AFI->hasSwiftAsyncContext()) {
  1298. switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
  1299. case SwiftAsyncFramePointerMode::DeploymentBased:
  1300. if (Subtarget.swiftAsyncContextIsDynamicallySet()) {
  1301. // The special symbol below is absolute and has a *value* that can be
  1302. // combined with the frame pointer to signal an extended frame.
  1303. BuildMI(MBB, MBBI, DL, TII->get(AArch64::LOADgot), AArch64::X16)
  1304. .addExternalSymbol("swift_async_extendedFramePointerFlags",
  1305. AArch64II::MO_GOT);
  1306. BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXrs), AArch64::FP)
  1307. .addUse(AArch64::FP)
  1308. .addUse(AArch64::X16)
  1309. .addImm(Subtarget.isTargetILP32() ? 32 : 0);
  1310. break;
  1311. }
  1312. [[fallthrough]];
  1313. case SwiftAsyncFramePointerMode::Always:
  1314. // ORR x29, x29, #0x1000_0000_0000_0000
  1315. BuildMI(MBB, MBBI, DL, TII->get(AArch64::ORRXri), AArch64::FP)
  1316. .addUse(AArch64::FP)
  1317. .addImm(0x1100)
  1318. .setMIFlag(MachineInstr::FrameSetup);
  1319. break;
  1320. case SwiftAsyncFramePointerMode::Never:
  1321. break;
  1322. }
  1323. }
  1324. // All calls are tail calls in GHC calling conv, and functions have no
  1325. // prologue/epilogue.
  1326. if (MF.getFunction().getCallingConv() == CallingConv::GHC)
  1327. return;
  1328. // Set tagged base pointer to the requested stack slot.
  1329. // Ideally it should match SP value after prologue.
  1330. std::optional<int> TBPI = AFI->getTaggedBasePointerIndex();
  1331. if (TBPI)
  1332. AFI->setTaggedBasePointerOffset(-MFI.getObjectOffset(*TBPI));
  1333. else
  1334. AFI->setTaggedBasePointerOffset(MFI.getStackSize());
  1335. const StackOffset &SVEStackSize = getSVEStackSize(MF);
  1336. // getStackSize() includes all the locals in its size calculation. We don't
  1337. // include these locals when computing the stack size of a funclet, as they
  1338. // are allocated in the parent's stack frame and accessed via the frame
  1339. // pointer from the funclet. We only save the callee saved registers in the
  1340. // funclet, which are really the callee saved registers of the parent
  1341. // function, including the funclet.
  1342. int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
  1343. : MFI.getStackSize();
  1344. if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) {
  1345. assert(!HasFP && "unexpected function without stack frame but with FP");
  1346. assert(!SVEStackSize &&
  1347. "unexpected function without stack frame but with SVE objects");
  1348. // All of the stack allocation is for locals.
  1349. AFI->setLocalStackSize(NumBytes);
  1350. if (!NumBytes)
  1351. return;
  1352. // REDZONE: If the stack size is less than 128 bytes, we don't need
  1353. // to actually allocate.
  1354. if (canUseRedZone(MF)) {
  1355. AFI->setHasRedZone(true);
  1356. ++NumRedZoneFunctions;
  1357. } else {
  1358. emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
  1359. StackOffset::getFixed(-NumBytes), TII,
  1360. MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
  1361. if (EmitCFI) {
  1362. // Label used to tie together the PROLOG_LABEL and the MachineMoves.
  1363. MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
  1364. // Encode the stack size of the leaf function.
  1365. unsigned CFIIndex = MF.addFrameInst(
  1366. MCCFIInstruction::cfiDefCfaOffset(FrameLabel, NumBytes));
  1367. BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  1368. .addCFIIndex(CFIIndex)
  1369. .setMIFlags(MachineInstr::FrameSetup);
  1370. }
  1371. }
  1372. if (NeedsWinCFI) {
  1373. HasWinCFI = true;
  1374. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
  1375. .setMIFlag(MachineInstr::FrameSetup);
  1376. }
  1377. return;
  1378. }
  1379. bool IsWin64 =
  1380. Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
  1381. unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
  1382. auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
  1383. // All of the remaining stack allocations are for locals.
  1384. AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
  1385. bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes);
  1386. bool HomPrologEpilog = homogeneousPrologEpilog(MF);
  1387. if (CombineSPBump) {
  1388. assert(!SVEStackSize && "Cannot combine SP bump with SVE");
  1389. emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP,
  1390. StackOffset::getFixed(-NumBytes), TII,
  1391. MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI,
  1392. EmitCFI);
  1393. NumBytes = 0;
  1394. } else if (HomPrologEpilog) {
  1395. // Stack has been already adjusted.
  1396. NumBytes -= PrologueSaveSize;
  1397. } else if (PrologueSaveSize != 0) {
  1398. MBBI = convertCalleeSaveRestoreToSPPrePostIncDec(
  1399. MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI, &HasWinCFI,
  1400. EmitCFI);
  1401. NumBytes -= PrologueSaveSize;
  1402. }
  1403. assert(NumBytes >= 0 && "Negative stack allocation size!?");
  1404. // Move past the saves of the callee-saved registers, fixing up the offsets
  1405. // and pre-inc if we decided to combine the callee-save and local stack
  1406. // pointer bump above.
  1407. MachineBasicBlock::iterator End = MBB.end();
  1408. while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup) &&
  1409. !IsSVECalleeSave(MBBI)) {
  1410. if (CombineSPBump)
  1411. fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(),
  1412. NeedsWinCFI, &HasWinCFI);
  1413. ++MBBI;
  1414. }
  1415. // For funclets the FP belongs to the containing function.
  1416. if (!IsFunclet && HasFP) {
  1417. // Only set up FP if we actually need to.
  1418. int64_t FPOffset = AFI->getCalleeSaveBaseToFrameRecordOffset();
  1419. if (CombineSPBump)
  1420. FPOffset += AFI->getLocalStackSize();
  1421. if (AFI->hasSwiftAsyncContext()) {
  1422. // Before we update the live FP we have to ensure there's a valid (or
  1423. // null) asynchronous context in its slot just before FP in the frame
  1424. // record, so store it now.
  1425. const auto &Attrs = MF.getFunction().getAttributes();
  1426. bool HaveInitialContext = Attrs.hasAttrSomewhere(Attribute::SwiftAsync);
  1427. if (HaveInitialContext)
  1428. MBB.addLiveIn(AArch64::X22);
  1429. BuildMI(MBB, MBBI, DL, TII->get(AArch64::StoreSwiftAsyncContext))
  1430. .addUse(HaveInitialContext ? AArch64::X22 : AArch64::XZR)
  1431. .addUse(AArch64::SP)
  1432. .addImm(FPOffset - 8)
  1433. .setMIFlags(MachineInstr::FrameSetup);
  1434. }
  1435. if (HomPrologEpilog) {
  1436. auto Prolog = MBBI;
  1437. --Prolog;
  1438. assert(Prolog->getOpcode() == AArch64::HOM_Prolog);
  1439. Prolog->addOperand(MachineOperand::CreateImm(FPOffset));
  1440. } else {
  1441. // Issue sub fp, sp, FPOffset or
  1442. // mov fp,sp when FPOffset is zero.
  1443. // Note: All stores of callee-saved registers are marked as "FrameSetup".
  1444. // This code marks the instruction(s) that set the FP also.
  1445. emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP,
  1446. StackOffset::getFixed(FPOffset), TII,
  1447. MachineInstr::FrameSetup, false, NeedsWinCFI, &HasWinCFI);
  1448. if (NeedsWinCFI && HasWinCFI) {
  1449. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
  1450. .setMIFlag(MachineInstr::FrameSetup);
  1451. // After setting up the FP, the rest of the prolog doesn't need to be
  1452. // included in the SEH unwind info.
  1453. NeedsWinCFI = false;
  1454. }
  1455. }
  1456. if (EmitCFI) {
  1457. // Define the current CFA rule to use the provided FP.
  1458. const int OffsetToFirstCalleeSaveFromFP =
  1459. AFI->getCalleeSaveBaseToFrameRecordOffset() -
  1460. AFI->getCalleeSavedStackSize();
  1461. Register FramePtr = RegInfo->getFrameRegister(MF);
  1462. unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
  1463. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
  1464. nullptr, Reg, FixedObject - OffsetToFirstCalleeSaveFromFP));
  1465. BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  1466. .addCFIIndex(CFIIndex)
  1467. .setMIFlags(MachineInstr::FrameSetup);
  1468. }
  1469. }
  1470. // Now emit the moves for whatever callee saved regs we have (including FP,
  1471. // LR if those are saved). Frame instructions for SVE register are emitted
  1472. // later, after the instruction which actually save SVE regs.
  1473. if (EmitCFI)
  1474. emitCalleeSavedGPRLocations(MBB, MBBI);
  1475. // Alignment is required for the parent frame, not the funclet
  1476. const bool NeedsRealignment =
  1477. NumBytes && !IsFunclet && RegInfo->hasStackRealignment(MF);
  1478. int64_t RealignmentPadding =
  1479. (NeedsRealignment && MFI.getMaxAlign() > Align(16))
  1480. ? MFI.getMaxAlign().value() - 16
  1481. : 0;
  1482. if (windowsRequiresStackProbe(MF, NumBytes + RealignmentPadding)) {
  1483. uint64_t NumWords = (NumBytes + RealignmentPadding) >> 4;
  1484. if (NeedsWinCFI) {
  1485. HasWinCFI = true;
  1486. // alloc_l can hold at most 256MB, so assume that NumBytes doesn't
  1487. // exceed this amount. We need to move at most 2^24 - 1 into x15.
  1488. // This is at most two instructions, MOVZ follwed by MOVK.
  1489. // TODO: Fix to use multiple stack alloc unwind codes for stacks
  1490. // exceeding 256MB in size.
  1491. if (NumBytes >= (1 << 28))
  1492. report_fatal_error("Stack size cannot exceed 256MB for stack "
  1493. "unwinding purposes");
  1494. uint32_t LowNumWords = NumWords & 0xFFFF;
  1495. BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15)
  1496. .addImm(LowNumWords)
  1497. .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
  1498. .setMIFlag(MachineInstr::FrameSetup);
  1499. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
  1500. .setMIFlag(MachineInstr::FrameSetup);
  1501. if ((NumWords & 0xFFFF0000) != 0) {
  1502. BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15)
  1503. .addReg(AArch64::X15)
  1504. .addImm((NumWords & 0xFFFF0000) >> 16) // High half
  1505. .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16))
  1506. .setMIFlag(MachineInstr::FrameSetup);
  1507. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
  1508. .setMIFlag(MachineInstr::FrameSetup);
  1509. }
  1510. } else {
  1511. BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15)
  1512. .addImm(NumWords)
  1513. .setMIFlags(MachineInstr::FrameSetup);
  1514. }
  1515. const char* ChkStk = Subtarget.getChkStkName();
  1516. switch (MF.getTarget().getCodeModel()) {
  1517. case CodeModel::Tiny:
  1518. case CodeModel::Small:
  1519. case CodeModel::Medium:
  1520. case CodeModel::Kernel:
  1521. BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL))
  1522. .addExternalSymbol(ChkStk)
  1523. .addReg(AArch64::X15, RegState::Implicit)
  1524. .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
  1525. .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
  1526. .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
  1527. .setMIFlags(MachineInstr::FrameSetup);
  1528. if (NeedsWinCFI) {
  1529. HasWinCFI = true;
  1530. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
  1531. .setMIFlag(MachineInstr::FrameSetup);
  1532. }
  1533. break;
  1534. case CodeModel::Large:
  1535. BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT))
  1536. .addReg(AArch64::X16, RegState::Define)
  1537. .addExternalSymbol(ChkStk)
  1538. .addExternalSymbol(ChkStk)
  1539. .setMIFlags(MachineInstr::FrameSetup);
  1540. if (NeedsWinCFI) {
  1541. HasWinCFI = true;
  1542. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
  1543. .setMIFlag(MachineInstr::FrameSetup);
  1544. }
  1545. BuildMI(MBB, MBBI, DL, TII->get(getBLRCallOpcode(MF)))
  1546. .addReg(AArch64::X16, RegState::Kill)
  1547. .addReg(AArch64::X15, RegState::Implicit | RegState::Define)
  1548. .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead)
  1549. .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead)
  1550. .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead)
  1551. .setMIFlags(MachineInstr::FrameSetup);
  1552. if (NeedsWinCFI) {
  1553. HasWinCFI = true;
  1554. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
  1555. .setMIFlag(MachineInstr::FrameSetup);
  1556. }
  1557. break;
  1558. }
  1559. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP)
  1560. .addReg(AArch64::SP, RegState::Kill)
  1561. .addReg(AArch64::X15, RegState::Kill)
  1562. .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4))
  1563. .setMIFlags(MachineInstr::FrameSetup);
  1564. if (NeedsWinCFI) {
  1565. HasWinCFI = true;
  1566. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
  1567. .addImm(NumBytes)
  1568. .setMIFlag(MachineInstr::FrameSetup);
  1569. }
  1570. NumBytes = 0;
  1571. if (RealignmentPadding > 0) {
  1572. BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDXri), AArch64::X15)
  1573. .addReg(AArch64::SP)
  1574. .addImm(RealignmentPadding)
  1575. .addImm(0);
  1576. uint64_t AndMask = ~(MFI.getMaxAlign().value() - 1);
  1577. BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
  1578. .addReg(AArch64::X15, RegState::Kill)
  1579. .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64));
  1580. AFI->setStackRealigned(true);
  1581. // No need for SEH instructions here; if we're realigning the stack,
  1582. // we've set a frame pointer and already finished the SEH prologue.
  1583. assert(!NeedsWinCFI);
  1584. }
  1585. }
  1586. StackOffset AllocateBefore = SVEStackSize, AllocateAfter = {};
  1587. MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
  1588. // Process the SVE callee-saves to determine what space needs to be
  1589. // allocated.
  1590. if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
  1591. // Find callee save instructions in frame.
  1592. CalleeSavesBegin = MBBI;
  1593. assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
  1594. while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
  1595. ++MBBI;
  1596. CalleeSavesEnd = MBBI;
  1597. AllocateBefore = StackOffset::getScalable(CalleeSavedSize);
  1598. AllocateAfter = SVEStackSize - AllocateBefore;
  1599. }
  1600. // Allocate space for the callee saves (if any).
  1601. emitFrameOffset(
  1602. MBB, CalleeSavesBegin, DL, AArch64::SP, AArch64::SP, -AllocateBefore, TII,
  1603. MachineInstr::FrameSetup, false, false, nullptr,
  1604. EmitCFI && !HasFP && AllocateBefore,
  1605. StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes));
  1606. if (EmitCFI)
  1607. emitCalleeSavedSVELocations(MBB, CalleeSavesEnd);
  1608. // Finally allocate remaining SVE stack space.
  1609. emitFrameOffset(MBB, CalleeSavesEnd, DL, AArch64::SP, AArch64::SP,
  1610. -AllocateAfter, TII, MachineInstr::FrameSetup, false, false,
  1611. nullptr, EmitCFI && !HasFP && AllocateAfter,
  1612. AllocateBefore + StackOffset::getFixed(
  1613. (int64_t)MFI.getStackSize() - NumBytes));
  1614. // Allocate space for the rest of the frame.
  1615. if (NumBytes) {
  1616. unsigned scratchSPReg = AArch64::SP;
  1617. if (NeedsRealignment) {
  1618. scratchSPReg = findScratchNonCalleeSaveRegister(&MBB);
  1619. assert(scratchSPReg != AArch64::NoRegister);
  1620. }
  1621. // If we're a leaf function, try using the red zone.
  1622. if (!canUseRedZone(MF)) {
  1623. // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
  1624. // the correct value here, as NumBytes also includes padding bytes,
  1625. // which shouldn't be counted here.
  1626. emitFrameOffset(
  1627. MBB, MBBI, DL, scratchSPReg, AArch64::SP,
  1628. StackOffset::getFixed(-NumBytes), TII, MachineInstr::FrameSetup,
  1629. false, NeedsWinCFI, &HasWinCFI, EmitCFI && !HasFP,
  1630. SVEStackSize +
  1631. StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes));
  1632. }
  1633. if (NeedsRealignment) {
  1634. assert(MFI.getMaxAlign() > Align(1));
  1635. assert(scratchSPReg != AArch64::SP);
  1636. // SUB X9, SP, NumBytes
  1637. // -- X9 is temporary register, so shouldn't contain any live data here,
  1638. // -- free to use. This is already produced by emitFrameOffset above.
  1639. // AND SP, X9, 0b11111...0000
  1640. uint64_t AndMask = ~(MFI.getMaxAlign().value() - 1);
  1641. BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
  1642. .addReg(scratchSPReg, RegState::Kill)
  1643. .addImm(AArch64_AM::encodeLogicalImmediate(AndMask, 64));
  1644. AFI->setStackRealigned(true);
  1645. // No need for SEH instructions here; if we're realigning the stack,
  1646. // we've set a frame pointer and already finished the SEH prologue.
  1647. assert(!NeedsWinCFI);
  1648. }
  1649. }
  1650. // If we need a base pointer, set it up here. It's whatever the value of the
  1651. // stack pointer is at this point. Any variable size objects will be allocated
  1652. // after this, so we can still use the base pointer to reference locals.
  1653. //
  1654. // FIXME: Clarify FrameSetup flags here.
  1655. // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
  1656. // needed.
  1657. // For funclets the BP belongs to the containing function.
  1658. if (!IsFunclet && RegInfo->hasBasePointer(MF)) {
  1659. TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
  1660. false);
  1661. if (NeedsWinCFI) {
  1662. HasWinCFI = true;
  1663. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop))
  1664. .setMIFlag(MachineInstr::FrameSetup);
  1665. }
  1666. }
  1667. // The very last FrameSetup instruction indicates the end of prologue. Emit a
  1668. // SEH opcode indicating the prologue end.
  1669. if (NeedsWinCFI && HasWinCFI) {
  1670. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd))
  1671. .setMIFlag(MachineInstr::FrameSetup);
  1672. }
  1673. // SEH funclets are passed the frame pointer in X1. If the parent
  1674. // function uses the base register, then the base register is used
  1675. // directly, and is not retrieved from X1.
  1676. if (IsFunclet && F.hasPersonalityFn()) {
  1677. EHPersonality Per = classifyEHPersonality(F.getPersonalityFn());
  1678. if (isAsynchronousEHPersonality(Per)) {
  1679. BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::COPY), AArch64::FP)
  1680. .addReg(AArch64::X1)
  1681. .setMIFlag(MachineInstr::FrameSetup);
  1682. MBB.addLiveIn(AArch64::X1);
  1683. }
  1684. }
  1685. }
  1686. static void InsertReturnAddressAuth(MachineFunction &MF, MachineBasicBlock &MBB,
  1687. bool NeedsWinCFI, bool *HasWinCFI) {
  1688. const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
  1689. if (!MFI.shouldSignReturnAddress(MF))
  1690. return;
  1691. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  1692. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  1693. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  1694. DebugLoc DL;
  1695. if (MBBI != MBB.end())
  1696. DL = MBBI->getDebugLoc();
  1697. // The AUTIASP instruction assembles to a hint instruction before v8.3a so
  1698. // this instruction can safely used for any v8a architecture.
  1699. // From v8.3a onwards there are optimised authenticate LR and return
  1700. // instructions, namely RETA{A,B}, that can be used instead. In this case the
  1701. // DW_CFA_AARCH64_negate_ra_state can't be emitted.
  1702. if (Subtarget.hasPAuth() &&
  1703. !MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack) &&
  1704. MBBI != MBB.end() && MBBI->getOpcode() == AArch64::RET_ReallyLR &&
  1705. !NeedsWinCFI) {
  1706. BuildMI(MBB, MBBI, DL,
  1707. TII->get(MFI.shouldSignWithBKey() ? AArch64::RETAB : AArch64::RETAA))
  1708. .copyImplicitOps(*MBBI);
  1709. MBB.erase(MBBI);
  1710. } else {
  1711. BuildMI(
  1712. MBB, MBBI, DL,
  1713. TII->get(MFI.shouldSignWithBKey() ? AArch64::AUTIBSP : AArch64::AUTIASP))
  1714. .setMIFlag(MachineInstr::FrameDestroy);
  1715. unsigned CFIIndex =
  1716. MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
  1717. BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  1718. .addCFIIndex(CFIIndex)
  1719. .setMIFlags(MachineInstr::FrameDestroy);
  1720. if (NeedsWinCFI) {
  1721. *HasWinCFI = true;
  1722. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PACSignLR))
  1723. .setMIFlag(MachineInstr::FrameDestroy);
  1724. }
  1725. }
  1726. }
  1727. static bool isFuncletReturnInstr(const MachineInstr &MI) {
  1728. switch (MI.getOpcode()) {
  1729. default:
  1730. return false;
  1731. case AArch64::CATCHRET:
  1732. case AArch64::CLEANUPRET:
  1733. return true;
  1734. }
  1735. }
  1736. void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
  1737. MachineBasicBlock &MBB) const {
  1738. MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
  1739. MachineFrameInfo &MFI = MF.getFrameInfo();
  1740. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  1741. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  1742. DebugLoc DL;
  1743. bool NeedsWinCFI = needsWinCFI(MF);
  1744. bool EmitCFI =
  1745. MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF);
  1746. bool HasWinCFI = false;
  1747. bool IsFunclet = false;
  1748. auto WinCFI = make_scope_exit([&]() { assert(HasWinCFI == MF.hasWinCFI()); });
  1749. if (MBB.end() != MBBI) {
  1750. DL = MBBI->getDebugLoc();
  1751. IsFunclet = isFuncletReturnInstr(*MBBI);
  1752. }
  1753. auto FinishingTouches = make_scope_exit([&]() {
  1754. InsertReturnAddressAuth(MF, MBB, NeedsWinCFI, &HasWinCFI);
  1755. if (needsShadowCallStackPrologueEpilogue(MF))
  1756. emitShadowCallStackEpilogue(*TII, MF, MBB, MBB.getFirstTerminator(), DL);
  1757. if (EmitCFI)
  1758. emitCalleeSavedGPRRestores(MBB, MBB.getFirstTerminator());
  1759. if (HasWinCFI)
  1760. BuildMI(MBB, MBB.getFirstTerminator(), DL,
  1761. TII->get(AArch64::SEH_EpilogEnd))
  1762. .setMIFlag(MachineInstr::FrameDestroy);
  1763. });
  1764. int64_t NumBytes = IsFunclet ? getWinEHFuncletFrameSize(MF)
  1765. : MFI.getStackSize();
  1766. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  1767. // All calls are tail calls in GHC calling conv, and functions have no
  1768. // prologue/epilogue.
  1769. if (MF.getFunction().getCallingConv() == CallingConv::GHC)
  1770. return;
  1771. // How much of the stack used by incoming arguments this function is expected
  1772. // to restore in this particular epilogue.
  1773. int64_t ArgumentStackToRestore = getArgumentStackToRestore(MF, MBB);
  1774. bool IsWin64 =
  1775. Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
  1776. unsigned FixedObject = getFixedObjectSize(MF, AFI, IsWin64, IsFunclet);
  1777. int64_t AfterCSRPopSize = ArgumentStackToRestore;
  1778. auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject;
  1779. // We cannot rely on the local stack size set in emitPrologue if the function
  1780. // has funclets, as funclets have different local stack size requirements, and
  1781. // the current value set in emitPrologue may be that of the containing
  1782. // function.
  1783. if (MF.hasEHFunclets())
  1784. AFI->setLocalStackSize(NumBytes - PrologueSaveSize);
  1785. if (homogeneousPrologEpilog(MF, &MBB)) {
  1786. assert(!NeedsWinCFI);
  1787. auto LastPopI = MBB.getFirstTerminator();
  1788. if (LastPopI != MBB.begin()) {
  1789. auto HomogeneousEpilog = std::prev(LastPopI);
  1790. if (HomogeneousEpilog->getOpcode() == AArch64::HOM_Epilog)
  1791. LastPopI = HomogeneousEpilog;
  1792. }
  1793. // Adjust local stack
  1794. emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
  1795. StackOffset::getFixed(AFI->getLocalStackSize()), TII,
  1796. MachineInstr::FrameDestroy, false, NeedsWinCFI);
  1797. // SP has been already adjusted while restoring callee save regs.
  1798. // We've bailed-out the case with adjusting SP for arguments.
  1799. assert(AfterCSRPopSize == 0);
  1800. return;
  1801. }
  1802. bool CombineSPBump = shouldCombineCSRLocalStackBumpInEpilogue(MBB, NumBytes);
  1803. // Assume we can't combine the last pop with the sp restore.
  1804. bool CombineAfterCSRBump = false;
  1805. if (!CombineSPBump && PrologueSaveSize != 0) {
  1806. MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator());
  1807. while (Pop->getOpcode() == TargetOpcode::CFI_INSTRUCTION ||
  1808. AArch64InstrInfo::isSEHInstruction(*Pop))
  1809. Pop = std::prev(Pop);
  1810. // Converting the last ldp to a post-index ldp is valid only if the last
  1811. // ldp's offset is 0.
  1812. const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1);
  1813. // If the offset is 0 and the AfterCSR pop is not actually trying to
  1814. // allocate more stack for arguments (in space that an untimely interrupt
  1815. // may clobber), convert it to a post-index ldp.
  1816. if (OffsetOp.getImm() == 0 && AfterCSRPopSize >= 0) {
  1817. convertCalleeSaveRestoreToSPPrePostIncDec(
  1818. MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, &HasWinCFI, EmitCFI,
  1819. MachineInstr::FrameDestroy, PrologueSaveSize);
  1820. } else {
  1821. // If not, make sure to emit an add after the last ldp.
  1822. // We're doing this by transfering the size to be restored from the
  1823. // adjustment *before* the CSR pops to the adjustment *after* the CSR
  1824. // pops.
  1825. AfterCSRPopSize += PrologueSaveSize;
  1826. CombineAfterCSRBump = true;
  1827. }
  1828. }
  1829. // Move past the restores of the callee-saved registers.
  1830. // If we plan on combining the sp bump of the local stack size and the callee
  1831. // save stack size, we might need to adjust the CSR save and restore offsets.
  1832. MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
  1833. MachineBasicBlock::iterator Begin = MBB.begin();
  1834. while (LastPopI != Begin) {
  1835. --LastPopI;
  1836. if (!LastPopI->getFlag(MachineInstr::FrameDestroy) ||
  1837. IsSVECalleeSave(LastPopI)) {
  1838. ++LastPopI;
  1839. break;
  1840. } else if (CombineSPBump)
  1841. fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(),
  1842. NeedsWinCFI, &HasWinCFI);
  1843. }
  1844. if (MF.hasWinCFI()) {
  1845. // If the prologue didn't contain any SEH opcodes and didn't set the
  1846. // MF.hasWinCFI() flag, assume the epilogue won't either, and skip the
  1847. // EpilogStart - to avoid generating CFI for functions that don't need it.
  1848. // (And as we didn't generate any prologue at all, it would be asymmetrical
  1849. // to the epilogue.) By the end of the function, we assert that
  1850. // HasWinCFI is equal to MF.hasWinCFI(), to verify this assumption.
  1851. HasWinCFI = true;
  1852. BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart))
  1853. .setMIFlag(MachineInstr::FrameDestroy);
  1854. }
  1855. if (hasFP(MF) && AFI->hasSwiftAsyncContext()) {
  1856. switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
  1857. case SwiftAsyncFramePointerMode::DeploymentBased:
  1858. // Avoid the reload as it is GOT relative, and instead fall back to the
  1859. // hardcoded value below. This allows a mismatch between the OS and
  1860. // application without immediately terminating on the difference.
  1861. [[fallthrough]];
  1862. case SwiftAsyncFramePointerMode::Always:
  1863. // We need to reset FP to its untagged state on return. Bit 60 is
  1864. // currently used to show the presence of an extended frame.
  1865. // BIC x29, x29, #0x1000_0000_0000_0000
  1866. BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::ANDXri),
  1867. AArch64::FP)
  1868. .addUse(AArch64::FP)
  1869. .addImm(0x10fe)
  1870. .setMIFlag(MachineInstr::FrameDestroy);
  1871. break;
  1872. case SwiftAsyncFramePointerMode::Never:
  1873. break;
  1874. }
  1875. }
  1876. const StackOffset &SVEStackSize = getSVEStackSize(MF);
  1877. // If there is a single SP update, insert it before the ret and we're done.
  1878. if (CombineSPBump) {
  1879. assert(!SVEStackSize && "Cannot combine SP bump with SVE");
  1880. // When we are about to restore the CSRs, the CFA register is SP again.
  1881. if (EmitCFI && hasFP(MF)) {
  1882. const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
  1883. unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
  1884. unsigned CFIIndex =
  1885. MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, NumBytes));
  1886. BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  1887. .addCFIIndex(CFIIndex)
  1888. .setMIFlags(MachineInstr::FrameDestroy);
  1889. }
  1890. emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
  1891. StackOffset::getFixed(NumBytes + (int64_t)AfterCSRPopSize),
  1892. TII, MachineInstr::FrameDestroy, false, NeedsWinCFI,
  1893. &HasWinCFI, EmitCFI, StackOffset::getFixed(NumBytes));
  1894. return;
  1895. }
  1896. NumBytes -= PrologueSaveSize;
  1897. assert(NumBytes >= 0 && "Negative stack allocation size!?");
  1898. // Process the SVE callee-saves to determine what space needs to be
  1899. // deallocated.
  1900. StackOffset DeallocateBefore = {}, DeallocateAfter = SVEStackSize;
  1901. MachineBasicBlock::iterator RestoreBegin = LastPopI, RestoreEnd = LastPopI;
  1902. if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
  1903. RestoreBegin = std::prev(RestoreEnd);
  1904. while (RestoreBegin != MBB.begin() &&
  1905. IsSVECalleeSave(std::prev(RestoreBegin)))
  1906. --RestoreBegin;
  1907. assert(IsSVECalleeSave(RestoreBegin) &&
  1908. IsSVECalleeSave(std::prev(RestoreEnd)) && "Unexpected instruction");
  1909. StackOffset CalleeSavedSizeAsOffset =
  1910. StackOffset::getScalable(CalleeSavedSize);
  1911. DeallocateBefore = SVEStackSize - CalleeSavedSizeAsOffset;
  1912. DeallocateAfter = CalleeSavedSizeAsOffset;
  1913. }
  1914. // Deallocate the SVE area.
  1915. if (SVEStackSize) {
  1916. // If we have stack realignment or variable sized objects on the stack,
  1917. // restore the stack pointer from the frame pointer prior to SVE CSR
  1918. // restoration.
  1919. if (AFI->isStackRealigned() || MFI.hasVarSizedObjects()) {
  1920. if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
  1921. // Set SP to start of SVE callee-save area from which they can
  1922. // be reloaded. The code below will deallocate the stack space
  1923. // space by moving FP -> SP.
  1924. emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::FP,
  1925. StackOffset::getScalable(-CalleeSavedSize), TII,
  1926. MachineInstr::FrameDestroy);
  1927. }
  1928. } else {
  1929. if (AFI->getSVECalleeSavedStackSize()) {
  1930. // Deallocate the non-SVE locals first before we can deallocate (and
  1931. // restore callee saves) from the SVE area.
  1932. emitFrameOffset(
  1933. MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
  1934. StackOffset::getFixed(NumBytes), TII, MachineInstr::FrameDestroy,
  1935. false, false, nullptr, EmitCFI && !hasFP(MF),
  1936. SVEStackSize + StackOffset::getFixed(NumBytes + PrologueSaveSize));
  1937. NumBytes = 0;
  1938. }
  1939. emitFrameOffset(MBB, RestoreBegin, DL, AArch64::SP, AArch64::SP,
  1940. DeallocateBefore, TII, MachineInstr::FrameDestroy, false,
  1941. false, nullptr, EmitCFI && !hasFP(MF),
  1942. SVEStackSize +
  1943. StackOffset::getFixed(NumBytes + PrologueSaveSize));
  1944. emitFrameOffset(MBB, RestoreEnd, DL, AArch64::SP, AArch64::SP,
  1945. DeallocateAfter, TII, MachineInstr::FrameDestroy, false,
  1946. false, nullptr, EmitCFI && !hasFP(MF),
  1947. DeallocateAfter +
  1948. StackOffset::getFixed(NumBytes + PrologueSaveSize));
  1949. }
  1950. if (EmitCFI)
  1951. emitCalleeSavedSVERestores(MBB, RestoreEnd);
  1952. }
  1953. if (!hasFP(MF)) {
  1954. bool RedZone = canUseRedZone(MF);
  1955. // If this was a redzone leaf function, we don't need to restore the
  1956. // stack pointer (but we may need to pop stack args for fastcc).
  1957. if (RedZone && AfterCSRPopSize == 0)
  1958. return;
  1959. // Pop the local variables off the stack. If there are no callee-saved
  1960. // registers, it means we are actually positioned at the terminator and can
  1961. // combine stack increment for the locals and the stack increment for
  1962. // callee-popped arguments into (possibly) a single instruction and be done.
  1963. bool NoCalleeSaveRestore = PrologueSaveSize == 0;
  1964. int64_t StackRestoreBytes = RedZone ? 0 : NumBytes;
  1965. if (NoCalleeSaveRestore)
  1966. StackRestoreBytes += AfterCSRPopSize;
  1967. emitFrameOffset(
  1968. MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
  1969. StackOffset::getFixed(StackRestoreBytes), TII,
  1970. MachineInstr::FrameDestroy, false, NeedsWinCFI, &HasWinCFI, EmitCFI,
  1971. StackOffset::getFixed((RedZone ? 0 : NumBytes) + PrologueSaveSize));
  1972. // If we were able to combine the local stack pop with the argument pop,
  1973. // then we're done.
  1974. if (NoCalleeSaveRestore || AfterCSRPopSize == 0) {
  1975. return;
  1976. }
  1977. NumBytes = 0;
  1978. }
  1979. // Restore the original stack pointer.
  1980. // FIXME: Rather than doing the math here, we should instead just use
  1981. // non-post-indexed loads for the restores if we aren't actually going to
  1982. // be able to save any instructions.
  1983. if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) {
  1984. emitFrameOffset(
  1985. MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
  1986. StackOffset::getFixed(-AFI->getCalleeSaveBaseToFrameRecordOffset()),
  1987. TII, MachineInstr::FrameDestroy, false, NeedsWinCFI);
  1988. } else if (NumBytes)
  1989. emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP,
  1990. StackOffset::getFixed(NumBytes), TII,
  1991. MachineInstr::FrameDestroy, false, NeedsWinCFI);
  1992. // When we are about to restore the CSRs, the CFA register is SP again.
  1993. if (EmitCFI && hasFP(MF)) {
  1994. const AArch64RegisterInfo &RegInfo = *Subtarget.getRegisterInfo();
  1995. unsigned Reg = RegInfo.getDwarfRegNum(AArch64::SP, true);
  1996. unsigned CFIIndex = MF.addFrameInst(
  1997. MCCFIInstruction::cfiDefCfa(nullptr, Reg, PrologueSaveSize));
  1998. BuildMI(MBB, LastPopI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  1999. .addCFIIndex(CFIIndex)
  2000. .setMIFlags(MachineInstr::FrameDestroy);
  2001. }
  2002. // This must be placed after the callee-save restore code because that code
  2003. // assumes the SP is at the same location as it was after the callee-save save
  2004. // code in the prologue.
  2005. if (AfterCSRPopSize) {
  2006. assert(AfterCSRPopSize > 0 && "attempting to reallocate arg stack that an "
  2007. "interrupt may have clobbered");
  2008. emitFrameOffset(
  2009. MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP,
  2010. StackOffset::getFixed(AfterCSRPopSize), TII, MachineInstr::FrameDestroy,
  2011. false, NeedsWinCFI, &HasWinCFI, EmitCFI,
  2012. StackOffset::getFixed(CombineAfterCSRBump ? PrologueSaveSize : 0));
  2013. }
  2014. }
  2015. /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
  2016. /// debug info. It's the same as what we use for resolving the code-gen
  2017. /// references for now. FIXME: This can go wrong when references are
  2018. /// SP-relative and simple call frames aren't used.
  2019. StackOffset
  2020. AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
  2021. Register &FrameReg) const {
  2022. return resolveFrameIndexReference(
  2023. MF, FI, FrameReg,
  2024. /*PreferFP=*/
  2025. MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress),
  2026. /*ForSimm=*/false);
  2027. }
  2028. StackOffset
  2029. AArch64FrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF,
  2030. int FI) const {
  2031. return StackOffset::getFixed(getSEHFrameIndexOffset(MF, FI));
  2032. }
  2033. static StackOffset getFPOffset(const MachineFunction &MF,
  2034. int64_t ObjectOffset) {
  2035. const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
  2036. const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  2037. bool IsWin64 =
  2038. Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv());
  2039. unsigned FixedObject =
  2040. getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false);
  2041. int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo());
  2042. int64_t FPAdjust =
  2043. CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset();
  2044. return StackOffset::getFixed(ObjectOffset + FixedObject + FPAdjust);
  2045. }
  2046. static StackOffset getStackOffset(const MachineFunction &MF,
  2047. int64_t ObjectOffset) {
  2048. const auto &MFI = MF.getFrameInfo();
  2049. return StackOffset::getFixed(ObjectOffset + (int64_t)MFI.getStackSize());
  2050. }
  2051. // TODO: This function currently does not work for scalable vectors.
  2052. int AArch64FrameLowering::getSEHFrameIndexOffset(const MachineFunction &MF,
  2053. int FI) const {
  2054. const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
  2055. MF.getSubtarget().getRegisterInfo());
  2056. int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
  2057. return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
  2058. ? getFPOffset(MF, ObjectOffset).getFixed()
  2059. : getStackOffset(MF, ObjectOffset).getFixed();
  2060. }
  2061. StackOffset AArch64FrameLowering::resolveFrameIndexReference(
  2062. const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP,
  2063. bool ForSimm) const {
  2064. const auto &MFI = MF.getFrameInfo();
  2065. int64_t ObjectOffset = MFI.getObjectOffset(FI);
  2066. bool isFixed = MFI.isFixedObjectIndex(FI);
  2067. bool isSVE = MFI.getStackID(FI) == TargetStackID::ScalableVector;
  2068. return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, isSVE, FrameReg,
  2069. PreferFP, ForSimm);
  2070. }
  2071. StackOffset AArch64FrameLowering::resolveFrameOffsetReference(
  2072. const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, bool isSVE,
  2073. Register &FrameReg, bool PreferFP, bool ForSimm) const {
  2074. const auto &MFI = MF.getFrameInfo();
  2075. const auto *RegInfo = static_cast<const AArch64RegisterInfo *>(
  2076. MF.getSubtarget().getRegisterInfo());
  2077. const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
  2078. const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  2079. int64_t FPOffset = getFPOffset(MF, ObjectOffset).getFixed();
  2080. int64_t Offset = getStackOffset(MF, ObjectOffset).getFixed();
  2081. bool isCSR =
  2082. !isFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
  2083. const StackOffset &SVEStackSize = getSVEStackSize(MF);
  2084. // Use frame pointer to reference fixed objects. Use it for locals if
  2085. // there are VLAs or a dynamically realigned SP (and thus the SP isn't
  2086. // reliable as a base). Make sure useFPForScavengingIndex() does the
  2087. // right thing for the emergency spill slot.
  2088. bool UseFP = false;
  2089. if (AFI->hasStackFrame() && !isSVE) {
  2090. // We shouldn't prefer using the FP to access fixed-sized stack objects when
  2091. // there are scalable (SVE) objects in between the FP and the fixed-sized
  2092. // objects.
  2093. PreferFP &= !SVEStackSize;
  2094. // Note: Keeping the following as multiple 'if' statements rather than
  2095. // merging to a single expression for readability.
  2096. //
  2097. // Argument access should always use the FP.
  2098. if (isFixed) {
  2099. UseFP = hasFP(MF);
  2100. } else if (isCSR && RegInfo->hasStackRealignment(MF)) {
  2101. // References to the CSR area must use FP if we're re-aligning the stack
  2102. // since the dynamically-sized alignment padding is between the SP/BP and
  2103. // the CSR area.
  2104. assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
  2105. UseFP = true;
  2106. } else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) {
  2107. // If the FPOffset is negative and we're producing a signed immediate, we
  2108. // have to keep in mind that the available offset range for negative
  2109. // offsets is smaller than for positive ones. If an offset is available
  2110. // via the FP and the SP, use whichever is closest.
  2111. bool FPOffsetFits = !ForSimm || FPOffset >= -256;
  2112. PreferFP |= Offset > -FPOffset && !SVEStackSize;
  2113. if (MFI.hasVarSizedObjects()) {
  2114. // If we have variable sized objects, we can use either FP or BP, as the
  2115. // SP offset is unknown. We can use the base pointer if we have one and
  2116. // FP is not preferred. If not, we're stuck with using FP.
  2117. bool CanUseBP = RegInfo->hasBasePointer(MF);
  2118. if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
  2119. UseFP = PreferFP;
  2120. else if (!CanUseBP) // Can't use BP. Forced to use FP.
  2121. UseFP = true;
  2122. // else we can use BP and FP, but the offset from FP won't fit.
  2123. // That will make us scavenge registers which we can probably avoid by
  2124. // using BP. If it won't fit for BP either, we'll scavenge anyway.
  2125. } else if (FPOffset >= 0) {
  2126. // Use SP or FP, whichever gives us the best chance of the offset
  2127. // being in range for direct access. If the FPOffset is positive,
  2128. // that'll always be best, as the SP will be even further away.
  2129. UseFP = true;
  2130. } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
  2131. // Funclets access the locals contained in the parent's stack frame
  2132. // via the frame pointer, so we have to use the FP in the parent
  2133. // function.
  2134. (void) Subtarget;
  2135. assert(
  2136. Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) &&
  2137. "Funclets should only be present on Win64");
  2138. UseFP = true;
  2139. } else {
  2140. // We have the choice between FP and (SP or BP).
  2141. if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
  2142. UseFP = true;
  2143. }
  2144. }
  2145. }
  2146. assert(
  2147. ((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) &&
  2148. "In the presence of dynamic stack pointer realignment, "
  2149. "non-argument/CSR objects cannot be accessed through the frame pointer");
  2150. if (isSVE) {
  2151. StackOffset FPOffset =
  2152. StackOffset::get(-AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset);
  2153. StackOffset SPOffset =
  2154. SVEStackSize +
  2155. StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(),
  2156. ObjectOffset);
  2157. // Always use the FP for SVE spills if available and beneficial.
  2158. if (hasFP(MF) && (SPOffset.getFixed() ||
  2159. FPOffset.getScalable() < SPOffset.getScalable() ||
  2160. RegInfo->hasStackRealignment(MF))) {
  2161. FrameReg = RegInfo->getFrameRegister(MF);
  2162. return FPOffset;
  2163. }
  2164. FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
  2165. : (unsigned)AArch64::SP;
  2166. return SPOffset;
  2167. }
  2168. StackOffset ScalableOffset = {};
  2169. if (UseFP && !(isFixed || isCSR))
  2170. ScalableOffset = -SVEStackSize;
  2171. if (!UseFP && (isFixed || isCSR))
  2172. ScalableOffset = SVEStackSize;
  2173. if (UseFP) {
  2174. FrameReg = RegInfo->getFrameRegister(MF);
  2175. return StackOffset::getFixed(FPOffset) + ScalableOffset;
  2176. }
  2177. // Use the base pointer if we have one.
  2178. if (RegInfo->hasBasePointer(MF))
  2179. FrameReg = RegInfo->getBaseRegister();
  2180. else {
  2181. assert(!MFI.hasVarSizedObjects() &&
  2182. "Can't use SP when we have var sized objects.");
  2183. FrameReg = AArch64::SP;
  2184. // If we're using the red zone for this function, the SP won't actually
  2185. // be adjusted, so the offsets will be negative. They're also all
  2186. // within range of the signed 9-bit immediate instructions.
  2187. if (canUseRedZone(MF))
  2188. Offset -= AFI->getLocalStackSize();
  2189. }
  2190. return StackOffset::getFixed(Offset) + ScalableOffset;
  2191. }
  2192. static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
  2193. // Do not set a kill flag on values that are also marked as live-in. This
  2194. // happens with the @llvm-returnaddress intrinsic and with arguments passed in
  2195. // callee saved registers.
  2196. // Omitting the kill flags is conservatively correct even if the live-in
  2197. // is not used after all.
  2198. bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
  2199. return getKillRegState(!IsLiveIn);
  2200. }
  2201. static bool produceCompactUnwindFrame(MachineFunction &MF) {
  2202. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  2203. AttributeList Attrs = MF.getFunction().getAttributes();
  2204. return Subtarget.isTargetMachO() &&
  2205. !(Subtarget.getTargetLowering()->supportSwiftError() &&
  2206. Attrs.hasAttrSomewhere(Attribute::SwiftError)) &&
  2207. MF.getFunction().getCallingConv() != CallingConv::SwiftTail;
  2208. }
  2209. static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2,
  2210. bool NeedsWinCFI, bool IsFirst,
  2211. const TargetRegisterInfo *TRI) {
  2212. // If we are generating register pairs for a Windows function that requires
  2213. // EH support, then pair consecutive registers only. There are no unwind
  2214. // opcodes for saves/restores of non-consectuve register pairs.
  2215. // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,
  2216. // save_lrpair.
  2217. // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
  2218. if (Reg2 == AArch64::FP)
  2219. return true;
  2220. if (!NeedsWinCFI)
  2221. return false;
  2222. if (TRI->getEncodingValue(Reg2) == TRI->getEncodingValue(Reg1) + 1)
  2223. return false;
  2224. // If pairing a GPR with LR, the pair can be described by the save_lrpair
  2225. // opcode. If this is the first register pair, it would end up with a
  2226. // predecrement, but there's no save_lrpair_x opcode, so we can only do this
  2227. // if LR is paired with something else than the first register.
  2228. // The save_lrpair opcode requires the first register to be an odd one.
  2229. if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 &&
  2230. (Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR && !IsFirst)
  2231. return false;
  2232. return true;
  2233. }
  2234. /// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
  2235. /// WindowsCFI requires that only consecutive registers can be paired.
  2236. /// LR and FP need to be allocated together when the frame needs to save
  2237. /// the frame-record. This means any other register pairing with LR is invalid.
  2238. static bool invalidateRegisterPairing(unsigned Reg1, unsigned Reg2,
  2239. bool UsesWinAAPCS, bool NeedsWinCFI,
  2240. bool NeedsFrameRecord, bool IsFirst,
  2241. const TargetRegisterInfo *TRI) {
  2242. if (UsesWinAAPCS)
  2243. return invalidateWindowsRegisterPairing(Reg1, Reg2, NeedsWinCFI, IsFirst,
  2244. TRI);
  2245. // If we need to store the frame record, don't pair any register
  2246. // with LR other than FP.
  2247. if (NeedsFrameRecord)
  2248. return Reg2 == AArch64::LR;
  2249. return false;
  2250. }
  2251. namespace {
  2252. struct RegPairInfo {
  2253. unsigned Reg1 = AArch64::NoRegister;
  2254. unsigned Reg2 = AArch64::NoRegister;
  2255. int FrameIdx;
  2256. int Offset;
  2257. enum RegType { GPR, FPR64, FPR128, PPR, ZPR } Type;
  2258. RegPairInfo() = default;
  2259. bool isPaired() const { return Reg2 != AArch64::NoRegister; }
  2260. unsigned getScale() const {
  2261. switch (Type) {
  2262. case PPR:
  2263. return 2;
  2264. case GPR:
  2265. case FPR64:
  2266. return 8;
  2267. case ZPR:
  2268. case FPR128:
  2269. return 16;
  2270. }
  2271. llvm_unreachable("Unsupported type");
  2272. }
  2273. bool isScalable() const { return Type == PPR || Type == ZPR; }
  2274. };
  2275. } // end anonymous namespace
  2276. static void computeCalleeSaveRegisterPairs(
  2277. MachineFunction &MF, ArrayRef<CalleeSavedInfo> CSI,
  2278. const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs,
  2279. bool NeedsFrameRecord) {
  2280. if (CSI.empty())
  2281. return;
  2282. bool IsWindows = isTargetWindows(MF);
  2283. bool NeedsWinCFI = needsWinCFI(MF);
  2284. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  2285. MachineFrameInfo &MFI = MF.getFrameInfo();
  2286. CallingConv::ID CC = MF.getFunction().getCallingConv();
  2287. unsigned Count = CSI.size();
  2288. (void)CC;
  2289. // MachO's compact unwind format relies on all registers being stored in
  2290. // pairs.
  2291. assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||
  2292. CC == CallingConv::CXX_FAST_TLS || CC == CallingConv::Win64 ||
  2293. (Count & 1) == 0) &&
  2294. "Odd number of callee-saved regs to spill!");
  2295. int ByteOffset = AFI->getCalleeSavedStackSize();
  2296. int StackFillDir = -1;
  2297. int RegInc = 1;
  2298. unsigned FirstReg = 0;
  2299. if (NeedsWinCFI) {
  2300. // For WinCFI, fill the stack from the bottom up.
  2301. ByteOffset = 0;
  2302. StackFillDir = 1;
  2303. // As the CSI array is reversed to match PrologEpilogInserter, iterate
  2304. // backwards, to pair up registers starting from lower numbered registers.
  2305. RegInc = -1;
  2306. FirstReg = Count - 1;
  2307. }
  2308. int ScalableByteOffset = AFI->getSVECalleeSavedStackSize();
  2309. bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace();
  2310. // When iterating backwards, the loop condition relies on unsigned wraparound.
  2311. for (unsigned i = FirstReg; i < Count; i += RegInc) {
  2312. RegPairInfo RPI;
  2313. RPI.Reg1 = CSI[i].getReg();
  2314. if (AArch64::GPR64RegClass.contains(RPI.Reg1))
  2315. RPI.Type = RegPairInfo::GPR;
  2316. else if (AArch64::FPR64RegClass.contains(RPI.Reg1))
  2317. RPI.Type = RegPairInfo::FPR64;
  2318. else if (AArch64::FPR128RegClass.contains(RPI.Reg1))
  2319. RPI.Type = RegPairInfo::FPR128;
  2320. else if (AArch64::ZPRRegClass.contains(RPI.Reg1))
  2321. RPI.Type = RegPairInfo::ZPR;
  2322. else if (AArch64::PPRRegClass.contains(RPI.Reg1))
  2323. RPI.Type = RegPairInfo::PPR;
  2324. else
  2325. llvm_unreachable("Unsupported register class.");
  2326. // Add the next reg to the pair if it is in the same register class.
  2327. if (unsigned(i + RegInc) < Count) {
  2328. Register NextReg = CSI[i + RegInc].getReg();
  2329. bool IsFirst = i == FirstReg;
  2330. switch (RPI.Type) {
  2331. case RegPairInfo::GPR:
  2332. if (AArch64::GPR64RegClass.contains(NextReg) &&
  2333. !invalidateRegisterPairing(RPI.Reg1, NextReg, IsWindows,
  2334. NeedsWinCFI, NeedsFrameRecord, IsFirst,
  2335. TRI))
  2336. RPI.Reg2 = NextReg;
  2337. break;
  2338. case RegPairInfo::FPR64:
  2339. if (AArch64::FPR64RegClass.contains(NextReg) &&
  2340. !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI,
  2341. IsFirst, TRI))
  2342. RPI.Reg2 = NextReg;
  2343. break;
  2344. case RegPairInfo::FPR128:
  2345. if (AArch64::FPR128RegClass.contains(NextReg))
  2346. RPI.Reg2 = NextReg;
  2347. break;
  2348. case RegPairInfo::PPR:
  2349. case RegPairInfo::ZPR:
  2350. break;
  2351. }
  2352. }
  2353. // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
  2354. // list to come in sorted by frame index so that we can issue the store
  2355. // pair instructions directly. Assert if we see anything otherwise.
  2356. //
  2357. // The order of the registers in the list is controlled by
  2358. // getCalleeSavedRegs(), so they will always be in-order, as well.
  2359. assert((!RPI.isPaired() ||
  2360. (CSI[i].getFrameIdx() + RegInc == CSI[i + RegInc].getFrameIdx())) &&
  2361. "Out of order callee saved regs!");
  2362. assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg2 != AArch64::FP ||
  2363. RPI.Reg1 == AArch64::LR) &&
  2364. "FrameRecord must be allocated together with LR");
  2365. // Windows AAPCS has FP and LR reversed.
  2366. assert((!RPI.isPaired() || !NeedsFrameRecord || RPI.Reg1 != AArch64::FP ||
  2367. RPI.Reg2 == AArch64::LR) &&
  2368. "FrameRecord must be allocated together with LR");
  2369. // MachO's compact unwind format relies on all registers being stored in
  2370. // adjacent register pairs.
  2371. assert((!produceCompactUnwindFrame(MF) || CC == CallingConv::PreserveMost ||
  2372. CC == CallingConv::CXX_FAST_TLS || CC == CallingConv::Win64 ||
  2373. (RPI.isPaired() &&
  2374. ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) ||
  2375. RPI.Reg1 + 1 == RPI.Reg2))) &&
  2376. "Callee-save registers not saved as adjacent register pair!");
  2377. RPI.FrameIdx = CSI[i].getFrameIdx();
  2378. if (NeedsWinCFI &&
  2379. RPI.isPaired()) // RPI.FrameIdx must be the lower index of the pair
  2380. RPI.FrameIdx = CSI[i + RegInc].getFrameIdx();
  2381. int Scale = RPI.getScale();
  2382. int OffsetPre = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
  2383. assert(OffsetPre % Scale == 0);
  2384. if (RPI.isScalable())
  2385. ScalableByteOffset += StackFillDir * Scale;
  2386. else
  2387. ByteOffset += StackFillDir * (RPI.isPaired() ? 2 * Scale : Scale);
  2388. // Swift's async context is directly before FP, so allocate an extra
  2389. // 8 bytes for it.
  2390. if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
  2391. RPI.Reg2 == AArch64::FP)
  2392. ByteOffset += StackFillDir * 8;
  2393. assert(!(RPI.isScalable() && RPI.isPaired()) &&
  2394. "Paired spill/fill instructions don't exist for SVE vectors");
  2395. // Round up size of non-pair to pair size if we need to pad the
  2396. // callee-save area to ensure 16-byte alignment.
  2397. if (NeedGapToAlignStack && !NeedsWinCFI &&
  2398. !RPI.isScalable() && RPI.Type != RegPairInfo::FPR128 &&
  2399. !RPI.isPaired() && ByteOffset % 16 != 0) {
  2400. ByteOffset += 8 * StackFillDir;
  2401. assert(MFI.getObjectAlign(RPI.FrameIdx) <= Align(16));
  2402. // A stack frame with a gap looks like this, bottom up:
  2403. // d9, d8. x21, gap, x20, x19.
  2404. // Set extra alignment on the x21 object to create the gap above it.
  2405. MFI.setObjectAlignment(RPI.FrameIdx, Align(16));
  2406. NeedGapToAlignStack = false;
  2407. }
  2408. int OffsetPost = RPI.isScalable() ? ScalableByteOffset : ByteOffset;
  2409. assert(OffsetPost % Scale == 0);
  2410. // If filling top down (default), we want the offset after incrementing it.
  2411. // If fillibg bootom up (WinCFI) we need the original offset.
  2412. int Offset = NeedsWinCFI ? OffsetPre : OffsetPost;
  2413. // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the
  2414. // Swift context can directly precede FP.
  2415. if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
  2416. RPI.Reg2 == AArch64::FP)
  2417. Offset += 8;
  2418. RPI.Offset = Offset / Scale;
  2419. assert(((!RPI.isScalable() && RPI.Offset >= -64 && RPI.Offset <= 63) ||
  2420. (RPI.isScalable() && RPI.Offset >= -256 && RPI.Offset <= 255)) &&
  2421. "Offset out of bounds for LDP/STP immediate");
  2422. // Save the offset to frame record so that the FP register can point to the
  2423. // innermost frame record (spilled FP and LR registers).
  2424. if (NeedsFrameRecord && ((!IsWindows && RPI.Reg1 == AArch64::LR &&
  2425. RPI.Reg2 == AArch64::FP) ||
  2426. (IsWindows && RPI.Reg1 == AArch64::FP &&
  2427. RPI.Reg2 == AArch64::LR)))
  2428. AFI->setCalleeSaveBaseToFrameRecordOffset(Offset);
  2429. RegPairs.push_back(RPI);
  2430. if (RPI.isPaired())
  2431. i += RegInc;
  2432. }
  2433. if (NeedsWinCFI) {
  2434. // If we need an alignment gap in the stack, align the topmost stack
  2435. // object. A stack frame with a gap looks like this, bottom up:
  2436. // x19, d8. d9, gap.
  2437. // Set extra alignment on the topmost stack object (the first element in
  2438. // CSI, which goes top down), to create the gap above it.
  2439. if (AFI->hasCalleeSaveStackFreeSpace())
  2440. MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16));
  2441. // We iterated bottom up over the registers; flip RegPairs back to top
  2442. // down order.
  2443. std::reverse(RegPairs.begin(), RegPairs.end());
  2444. }
  2445. }
  2446. bool AArch64FrameLowering::spillCalleeSavedRegisters(
  2447. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  2448. ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  2449. MachineFunction &MF = *MBB.getParent();
  2450. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  2451. bool NeedsWinCFI = needsWinCFI(MF);
  2452. DebugLoc DL;
  2453. SmallVector<RegPairInfo, 8> RegPairs;
  2454. computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
  2455. const MachineRegisterInfo &MRI = MF.getRegInfo();
  2456. if (homogeneousPrologEpilog(MF)) {
  2457. auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog))
  2458. .setMIFlag(MachineInstr::FrameSetup);
  2459. for (auto &RPI : RegPairs) {
  2460. MIB.addReg(RPI.Reg1);
  2461. MIB.addReg(RPI.Reg2);
  2462. // Update register live in.
  2463. if (!MRI.isReserved(RPI.Reg1))
  2464. MBB.addLiveIn(RPI.Reg1);
  2465. if (!MRI.isReserved(RPI.Reg2))
  2466. MBB.addLiveIn(RPI.Reg2);
  2467. }
  2468. return true;
  2469. }
  2470. for (const RegPairInfo &RPI : llvm::reverse(RegPairs)) {
  2471. unsigned Reg1 = RPI.Reg1;
  2472. unsigned Reg2 = RPI.Reg2;
  2473. unsigned StrOpc;
  2474. // Issue sequence of spills for cs regs. The first spill may be converted
  2475. // to a pre-decrement store later by emitPrologue if the callee-save stack
  2476. // area allocation can't be combined with the local stack area allocation.
  2477. // For example:
  2478. // stp x22, x21, [sp, #0] // addImm(+0)
  2479. // stp x20, x19, [sp, #16] // addImm(+2)
  2480. // stp fp, lr, [sp, #32] // addImm(+4)
  2481. // Rationale: This sequence saves uop updates compared to a sequence of
  2482. // pre-increment spills like stp xi,xj,[sp,#-16]!
  2483. // Note: Similar rationale and sequence for restores in epilog.
  2484. unsigned Size;
  2485. Align Alignment;
  2486. switch (RPI.Type) {
  2487. case RegPairInfo::GPR:
  2488. StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
  2489. Size = 8;
  2490. Alignment = Align(8);
  2491. break;
  2492. case RegPairInfo::FPR64:
  2493. StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
  2494. Size = 8;
  2495. Alignment = Align(8);
  2496. break;
  2497. case RegPairInfo::FPR128:
  2498. StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
  2499. Size = 16;
  2500. Alignment = Align(16);
  2501. break;
  2502. case RegPairInfo::ZPR:
  2503. StrOpc = AArch64::STR_ZXI;
  2504. Size = 16;
  2505. Alignment = Align(16);
  2506. break;
  2507. case RegPairInfo::PPR:
  2508. StrOpc = AArch64::STR_PXI;
  2509. Size = 2;
  2510. Alignment = Align(2);
  2511. break;
  2512. }
  2513. LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI);
  2514. if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
  2515. dbgs() << ") -> fi#(" << RPI.FrameIdx;
  2516. if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
  2517. dbgs() << ")\n");
  2518. assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
  2519. "Windows unwdinding requires a consecutive (FP,LR) pair");
  2520. // Windows unwind codes require consecutive registers if registers are
  2521. // paired. Make the switch here, so that the code below will save (x,x+1)
  2522. // and not (x+1,x).
  2523. unsigned FrameIdxReg1 = RPI.FrameIdx;
  2524. unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
  2525. if (NeedsWinCFI && RPI.isPaired()) {
  2526. std::swap(Reg1, Reg2);
  2527. std::swap(FrameIdxReg1, FrameIdxReg2);
  2528. }
  2529. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
  2530. if (!MRI.isReserved(Reg1))
  2531. MBB.addLiveIn(Reg1);
  2532. if (RPI.isPaired()) {
  2533. if (!MRI.isReserved(Reg2))
  2534. MBB.addLiveIn(Reg2);
  2535. MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
  2536. MIB.addMemOperand(MF.getMachineMemOperand(
  2537. MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
  2538. MachineMemOperand::MOStore, Size, Alignment));
  2539. }
  2540. MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
  2541. .addReg(AArch64::SP)
  2542. .addImm(RPI.Offset) // [sp, #offset*scale],
  2543. // where factor*scale is implicit
  2544. .setMIFlag(MachineInstr::FrameSetup);
  2545. MIB.addMemOperand(MF.getMachineMemOperand(
  2546. MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
  2547. MachineMemOperand::MOStore, Size, Alignment));
  2548. if (NeedsWinCFI)
  2549. InsertSEH(MIB, TII, MachineInstr::FrameSetup);
  2550. // Update the StackIDs of the SVE stack slots.
  2551. MachineFrameInfo &MFI = MF.getFrameInfo();
  2552. if (RPI.Type == RegPairInfo::ZPR || RPI.Type == RegPairInfo::PPR)
  2553. MFI.setStackID(RPI.FrameIdx, TargetStackID::ScalableVector);
  2554. }
  2555. return true;
  2556. }
  2557. bool AArch64FrameLowering::restoreCalleeSavedRegisters(
  2558. MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
  2559. MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  2560. MachineFunction &MF = *MBB.getParent();
  2561. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  2562. DebugLoc DL;
  2563. SmallVector<RegPairInfo, 8> RegPairs;
  2564. bool NeedsWinCFI = needsWinCFI(MF);
  2565. if (MBBI != MBB.end())
  2566. DL = MBBI->getDebugLoc();
  2567. computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, hasFP(MF));
  2568. auto EmitMI = [&](const RegPairInfo &RPI) -> MachineBasicBlock::iterator {
  2569. unsigned Reg1 = RPI.Reg1;
  2570. unsigned Reg2 = RPI.Reg2;
  2571. // Issue sequence of restores for cs regs. The last restore may be converted
  2572. // to a post-increment load later by emitEpilogue if the callee-save stack
  2573. // area allocation can't be combined with the local stack area allocation.
  2574. // For example:
  2575. // ldp fp, lr, [sp, #32] // addImm(+4)
  2576. // ldp x20, x19, [sp, #16] // addImm(+2)
  2577. // ldp x22, x21, [sp, #0] // addImm(+0)
  2578. // Note: see comment in spillCalleeSavedRegisters()
  2579. unsigned LdrOpc;
  2580. unsigned Size;
  2581. Align Alignment;
  2582. switch (RPI.Type) {
  2583. case RegPairInfo::GPR:
  2584. LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
  2585. Size = 8;
  2586. Alignment = Align(8);
  2587. break;
  2588. case RegPairInfo::FPR64:
  2589. LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
  2590. Size = 8;
  2591. Alignment = Align(8);
  2592. break;
  2593. case RegPairInfo::FPR128:
  2594. LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
  2595. Size = 16;
  2596. Alignment = Align(16);
  2597. break;
  2598. case RegPairInfo::ZPR:
  2599. LdrOpc = AArch64::LDR_ZXI;
  2600. Size = 16;
  2601. Alignment = Align(16);
  2602. break;
  2603. case RegPairInfo::PPR:
  2604. LdrOpc = AArch64::LDR_PXI;
  2605. Size = 2;
  2606. Alignment = Align(2);
  2607. break;
  2608. }
  2609. LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI);
  2610. if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI);
  2611. dbgs() << ") -> fi#(" << RPI.FrameIdx;
  2612. if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1;
  2613. dbgs() << ")\n");
  2614. // Windows unwind codes require consecutive registers if registers are
  2615. // paired. Make the switch here, so that the code below will save (x,x+1)
  2616. // and not (x+1,x).
  2617. unsigned FrameIdxReg1 = RPI.FrameIdx;
  2618. unsigned FrameIdxReg2 = RPI.FrameIdx + 1;
  2619. if (NeedsWinCFI && RPI.isPaired()) {
  2620. std::swap(Reg1, Reg2);
  2621. std::swap(FrameIdxReg1, FrameIdxReg2);
  2622. }
  2623. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));
  2624. if (RPI.isPaired()) {
  2625. MIB.addReg(Reg2, getDefRegState(true));
  2626. MIB.addMemOperand(MF.getMachineMemOperand(
  2627. MachinePointerInfo::getFixedStack(MF, FrameIdxReg2),
  2628. MachineMemOperand::MOLoad, Size, Alignment));
  2629. }
  2630. MIB.addReg(Reg1, getDefRegState(true))
  2631. .addReg(AArch64::SP)
  2632. .addImm(RPI.Offset) // [sp, #offset*scale]
  2633. // where factor*scale is implicit
  2634. .setMIFlag(MachineInstr::FrameDestroy);
  2635. MIB.addMemOperand(MF.getMachineMemOperand(
  2636. MachinePointerInfo::getFixedStack(MF, FrameIdxReg1),
  2637. MachineMemOperand::MOLoad, Size, Alignment));
  2638. if (NeedsWinCFI)
  2639. InsertSEH(MIB, TII, MachineInstr::FrameDestroy);
  2640. return MIB->getIterator();
  2641. };
  2642. // SVE objects are always restored in reverse order.
  2643. for (const RegPairInfo &RPI : reverse(RegPairs))
  2644. if (RPI.isScalable())
  2645. EmitMI(RPI);
  2646. if (homogeneousPrologEpilog(MF, &MBB)) {
  2647. auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog))
  2648. .setMIFlag(MachineInstr::FrameDestroy);
  2649. for (auto &RPI : RegPairs) {
  2650. MIB.addReg(RPI.Reg1, RegState::Define);
  2651. MIB.addReg(RPI.Reg2, RegState::Define);
  2652. }
  2653. return true;
  2654. }
  2655. if (ReverseCSRRestoreSeq) {
  2656. MachineBasicBlock::iterator First = MBB.end();
  2657. for (const RegPairInfo &RPI : reverse(RegPairs)) {
  2658. if (RPI.isScalable())
  2659. continue;
  2660. MachineBasicBlock::iterator It = EmitMI(RPI);
  2661. if (First == MBB.end())
  2662. First = It;
  2663. }
  2664. if (First != MBB.end())
  2665. MBB.splice(MBBI, &MBB, First);
  2666. } else {
  2667. for (const RegPairInfo &RPI : RegPairs) {
  2668. if (RPI.isScalable())
  2669. continue;
  2670. (void)EmitMI(RPI);
  2671. }
  2672. }
  2673. return true;
  2674. }
  2675. void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
  2676. BitVector &SavedRegs,
  2677. RegScavenger *RS) const {
  2678. // All calls are tail calls in GHC calling conv, and functions have no
  2679. // prologue/epilogue.
  2680. if (MF.getFunction().getCallingConv() == CallingConv::GHC)
  2681. return;
  2682. TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
  2683. const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
  2684. MF.getSubtarget().getRegisterInfo());
  2685. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  2686. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  2687. unsigned UnspilledCSGPR = AArch64::NoRegister;
  2688. unsigned UnspilledCSGPRPaired = AArch64::NoRegister;
  2689. MachineFrameInfo &MFI = MF.getFrameInfo();
  2690. const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
  2691. unsigned BasePointerReg = RegInfo->hasBasePointer(MF)
  2692. ? RegInfo->getBaseRegister()
  2693. : (unsigned)AArch64::NoRegister;
  2694. unsigned ExtraCSSpill = 0;
  2695. // Figure out which callee-saved registers to save/restore.
  2696. for (unsigned i = 0; CSRegs[i]; ++i) {
  2697. const unsigned Reg = CSRegs[i];
  2698. // Add the base pointer register to SavedRegs if it is callee-save.
  2699. if (Reg == BasePointerReg)
  2700. SavedRegs.set(Reg);
  2701. bool RegUsed = SavedRegs.test(Reg);
  2702. unsigned PairedReg = AArch64::NoRegister;
  2703. if (AArch64::GPR64RegClass.contains(Reg) ||
  2704. AArch64::FPR64RegClass.contains(Reg) ||
  2705. AArch64::FPR128RegClass.contains(Reg))
  2706. PairedReg = CSRegs[i ^ 1];
  2707. if (!RegUsed) {
  2708. if (AArch64::GPR64RegClass.contains(Reg) &&
  2709. !RegInfo->isReservedReg(MF, Reg)) {
  2710. UnspilledCSGPR = Reg;
  2711. UnspilledCSGPRPaired = PairedReg;
  2712. }
  2713. continue;
  2714. }
  2715. // MachO's compact unwind format relies on all registers being stored in
  2716. // pairs.
  2717. // FIXME: the usual format is actually better if unwinding isn't needed.
  2718. if (producePairRegisters(MF) && PairedReg != AArch64::NoRegister &&
  2719. !SavedRegs.test(PairedReg)) {
  2720. SavedRegs.set(PairedReg);
  2721. if (AArch64::GPR64RegClass.contains(PairedReg) &&
  2722. !RegInfo->isReservedReg(MF, PairedReg))
  2723. ExtraCSSpill = PairedReg;
  2724. }
  2725. }
  2726. if (MF.getFunction().getCallingConv() == CallingConv::Win64 &&
  2727. !Subtarget.isTargetWindows()) {
  2728. // For Windows calling convention on a non-windows OS, where X18 is treated
  2729. // as reserved, back up X18 when entering non-windows code (marked with the
  2730. // Windows calling convention) and restore when returning regardless of
  2731. // whether the individual function uses it - it might call other functions
  2732. // that clobber it.
  2733. SavedRegs.set(AArch64::X18);
  2734. }
  2735. // Calculates the callee saved stack size.
  2736. unsigned CSStackSize = 0;
  2737. unsigned SVECSStackSize = 0;
  2738. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2739. const MachineRegisterInfo &MRI = MF.getRegInfo();
  2740. for (unsigned Reg : SavedRegs.set_bits()) {
  2741. auto RegSize = TRI->getRegSizeInBits(Reg, MRI) / 8;
  2742. if (AArch64::PPRRegClass.contains(Reg) ||
  2743. AArch64::ZPRRegClass.contains(Reg))
  2744. SVECSStackSize += RegSize;
  2745. else
  2746. CSStackSize += RegSize;
  2747. }
  2748. // Save number of saved regs, so we can easily update CSStackSize later.
  2749. unsigned NumSavedRegs = SavedRegs.count();
  2750. // The frame record needs to be created by saving the appropriate registers
  2751. uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
  2752. if (hasFP(MF) ||
  2753. windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
  2754. SavedRegs.set(AArch64::FP);
  2755. SavedRegs.set(AArch64::LR);
  2756. }
  2757. LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
  2758. for (unsigned Reg
  2759. : SavedRegs.set_bits()) dbgs()
  2760. << ' ' << printReg(Reg, RegInfo);
  2761. dbgs() << "\n";);
  2762. // If any callee-saved registers are used, the frame cannot be eliminated.
  2763. int64_t SVEStackSize =
  2764. alignTo(SVECSStackSize + estimateSVEStackObjectOffsets(MFI), 16);
  2765. bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
  2766. // The CSR spill slots have not been allocated yet, so estimateStackSize
  2767. // won't include them.
  2768. unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
  2769. // Conservatively always assume BigStack when there are SVE spills.
  2770. bool BigStack = SVEStackSize ||
  2771. (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit;
  2772. if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
  2773. AFI->setHasStackFrame(true);
  2774. // Estimate if we might need to scavenge a register at some point in order
  2775. // to materialize a stack offset. If so, either spill one additional
  2776. // callee-saved register or reserve a special spill slot to facilitate
  2777. // register scavenging. If we already spilled an extra callee-saved register
  2778. // above to keep the number of spills even, we don't need to do anything else
  2779. // here.
  2780. if (BigStack) {
  2781. if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) {
  2782. LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
  2783. << " to get a scratch register.\n");
  2784. SavedRegs.set(UnspilledCSGPR);
  2785. // MachO's compact unwind format relies on all registers being stored in
  2786. // pairs, so if we need to spill one extra for BigStack, then we need to
  2787. // store the pair.
  2788. if (producePairRegisters(MF))
  2789. SavedRegs.set(UnspilledCSGPRPaired);
  2790. ExtraCSSpill = UnspilledCSGPR;
  2791. }
  2792. // If we didn't find an extra callee-saved register to spill, create
  2793. // an emergency spill slot.
  2794. if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
  2795. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2796. const TargetRegisterClass &RC = AArch64::GPR64RegClass;
  2797. unsigned Size = TRI->getSpillSize(RC);
  2798. Align Alignment = TRI->getSpillAlign(RC);
  2799. int FI = MFI.CreateStackObject(Size, Alignment, false);
  2800. RS->addScavengingFrameIndex(FI);
  2801. LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
  2802. << " as the emergency spill slot.\n");
  2803. }
  2804. }
  2805. // Adding the size of additional 64bit GPR saves.
  2806. CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
  2807. // A Swift asynchronous context extends the frame record with a pointer
  2808. // directly before FP.
  2809. if (hasFP(MF) && AFI->hasSwiftAsyncContext())
  2810. CSStackSize += 8;
  2811. uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
  2812. LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
  2813. << EstimatedStackSize + AlignedCSStackSize
  2814. << " bytes.\n");
  2815. assert((!MFI.isCalleeSavedInfoValid() ||
  2816. AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
  2817. "Should not invalidate callee saved info");
  2818. // Round up to register pair alignment to avoid additional SP adjustment
  2819. // instructions.
  2820. AFI->setCalleeSavedStackSize(AlignedCSStackSize);
  2821. AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
  2822. AFI->setSVECalleeSavedStackSize(alignTo(SVECSStackSize, 16));
  2823. }
  2824. bool AArch64FrameLowering::assignCalleeSavedSpillSlots(
  2825. MachineFunction &MF, const TargetRegisterInfo *RegInfo,
  2826. std::vector<CalleeSavedInfo> &CSI, unsigned &MinCSFrameIndex,
  2827. unsigned &MaxCSFrameIndex) const {
  2828. bool NeedsWinCFI = needsWinCFI(MF);
  2829. // To match the canonical windows frame layout, reverse the list of
  2830. // callee saved registers to get them laid out by PrologEpilogInserter
  2831. // in the right order. (PrologEpilogInserter allocates stack objects top
  2832. // down. Windows canonical prologs store higher numbered registers at
  2833. // the top, thus have the CSI array start from the highest registers.)
  2834. if (NeedsWinCFI)
  2835. std::reverse(CSI.begin(), CSI.end());
  2836. if (CSI.empty())
  2837. return true; // Early exit if no callee saved registers are modified!
  2838. // Now that we know which registers need to be saved and restored, allocate
  2839. // stack slots for them.
  2840. MachineFrameInfo &MFI = MF.getFrameInfo();
  2841. auto *AFI = MF.getInfo<AArch64FunctionInfo>();
  2842. bool UsesWinAAPCS = isTargetWindows(MF);
  2843. if (UsesWinAAPCS && hasFP(MF) && AFI->hasSwiftAsyncContext()) {
  2844. int FrameIdx = MFI.CreateStackObject(8, Align(16), true);
  2845. AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
  2846. if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
  2847. if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
  2848. }
  2849. for (auto &CS : CSI) {
  2850. Register Reg = CS.getReg();
  2851. const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
  2852. unsigned Size = RegInfo->getSpillSize(*RC);
  2853. Align Alignment(RegInfo->getSpillAlign(*RC));
  2854. int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
  2855. CS.setFrameIdx(FrameIdx);
  2856. if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
  2857. if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
  2858. // Grab 8 bytes below FP for the extended asynchronous frame info.
  2859. if (hasFP(MF) && AFI->hasSwiftAsyncContext() && !UsesWinAAPCS &&
  2860. Reg == AArch64::FP) {
  2861. FrameIdx = MFI.CreateStackObject(8, Alignment, true);
  2862. AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
  2863. if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
  2864. if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
  2865. }
  2866. }
  2867. return true;
  2868. }
  2869. bool AArch64FrameLowering::enableStackSlotScavenging(
  2870. const MachineFunction &MF) const {
  2871. const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  2872. return AFI->hasCalleeSaveStackFreeSpace();
  2873. }
  2874. /// returns true if there are any SVE callee saves.
  2875. static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI,
  2876. int &Min, int &Max) {
  2877. Min = std::numeric_limits<int>::max();
  2878. Max = std::numeric_limits<int>::min();
  2879. if (!MFI.isCalleeSavedInfoValid())
  2880. return false;
  2881. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  2882. for (auto &CS : CSI) {
  2883. if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
  2884. AArch64::PPRRegClass.contains(CS.getReg())) {
  2885. assert((Max == std::numeric_limits<int>::min() ||
  2886. Max + 1 == CS.getFrameIdx()) &&
  2887. "SVE CalleeSaves are not consecutive");
  2888. Min = std::min(Min, CS.getFrameIdx());
  2889. Max = std::max(Max, CS.getFrameIdx());
  2890. }
  2891. }
  2892. return Min != std::numeric_limits<int>::max();
  2893. }
  2894. // Process all the SVE stack objects and determine offsets for each
  2895. // object. If AssignOffsets is true, the offsets get assigned.
  2896. // Fills in the first and last callee-saved frame indices into
  2897. // Min/MaxCSFrameIndex, respectively.
  2898. // Returns the size of the stack.
  2899. static int64_t determineSVEStackObjectOffsets(MachineFrameInfo &MFI,
  2900. int &MinCSFrameIndex,
  2901. int &MaxCSFrameIndex,
  2902. bool AssignOffsets) {
  2903. #ifndef NDEBUG
  2904. // First process all fixed stack objects.
  2905. for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
  2906. assert(MFI.getStackID(I) != TargetStackID::ScalableVector &&
  2907. "SVE vectors should never be passed on the stack by value, only by "
  2908. "reference.");
  2909. #endif
  2910. auto Assign = [&MFI](int FI, int64_t Offset) {
  2911. LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
  2912. MFI.setObjectOffset(FI, Offset);
  2913. };
  2914. int64_t Offset = 0;
  2915. // Then process all callee saved slots.
  2916. if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
  2917. // Assign offsets to the callee save slots.
  2918. for (int I = MinCSFrameIndex; I <= MaxCSFrameIndex; ++I) {
  2919. Offset += MFI.getObjectSize(I);
  2920. Offset = alignTo(Offset, MFI.getObjectAlign(I));
  2921. if (AssignOffsets)
  2922. Assign(I, -Offset);
  2923. }
  2924. }
  2925. // Ensure that the Callee-save area is aligned to 16bytes.
  2926. Offset = alignTo(Offset, Align(16U));
  2927. // Create a buffer of SVE objects to allocate and sort it.
  2928. SmallVector<int, 8> ObjectsToAllocate;
  2929. // If we have a stack protector, and we've previously decided that we have SVE
  2930. // objects on the stack and thus need it to go in the SVE stack area, then it
  2931. // needs to go first.
  2932. int StackProtectorFI = -1;
  2933. if (MFI.hasStackProtectorIndex()) {
  2934. StackProtectorFI = MFI.getStackProtectorIndex();
  2935. if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector)
  2936. ObjectsToAllocate.push_back(StackProtectorFI);
  2937. }
  2938. for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
  2939. unsigned StackID = MFI.getStackID(I);
  2940. if (StackID != TargetStackID::ScalableVector)
  2941. continue;
  2942. if (I == StackProtectorFI)
  2943. continue;
  2944. if (MaxCSFrameIndex >= I && I >= MinCSFrameIndex)
  2945. continue;
  2946. if (MFI.isDeadObjectIndex(I))
  2947. continue;
  2948. ObjectsToAllocate.push_back(I);
  2949. }
  2950. // Allocate all SVE locals and spills
  2951. for (unsigned FI : ObjectsToAllocate) {
  2952. Align Alignment = MFI.getObjectAlign(FI);
  2953. // FIXME: Given that the length of SVE vectors is not necessarily a power of
  2954. // two, we'd need to align every object dynamically at runtime if the
  2955. // alignment is larger than 16. This is not yet supported.
  2956. if (Alignment > Align(16))
  2957. report_fatal_error(
  2958. "Alignment of scalable vectors > 16 bytes is not yet supported");
  2959. Offset = alignTo(Offset + MFI.getObjectSize(FI), Alignment);
  2960. if (AssignOffsets)
  2961. Assign(FI, -Offset);
  2962. }
  2963. return Offset;
  2964. }
  2965. int64_t AArch64FrameLowering::estimateSVEStackObjectOffsets(
  2966. MachineFrameInfo &MFI) const {
  2967. int MinCSFrameIndex, MaxCSFrameIndex;
  2968. return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex, false);
  2969. }
  2970. int64_t AArch64FrameLowering::assignSVEStackObjectOffsets(
  2971. MachineFrameInfo &MFI, int &MinCSFrameIndex, int &MaxCSFrameIndex) const {
  2972. return determineSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex,
  2973. true);
  2974. }
  2975. void AArch64FrameLowering::processFunctionBeforeFrameFinalized(
  2976. MachineFunction &MF, RegScavenger *RS) const {
  2977. MachineFrameInfo &MFI = MF.getFrameInfo();
  2978. assert(getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown &&
  2979. "Upwards growing stack unsupported");
  2980. int MinCSFrameIndex, MaxCSFrameIndex;
  2981. int64_t SVEStackSize =
  2982. assignSVEStackObjectOffsets(MFI, MinCSFrameIndex, MaxCSFrameIndex);
  2983. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  2984. AFI->setStackSizeSVE(alignTo(SVEStackSize, 16U));
  2985. AFI->setMinMaxSVECSFrameIndex(MinCSFrameIndex, MaxCSFrameIndex);
  2986. // If this function isn't doing Win64-style C++ EH, we don't need to do
  2987. // anything.
  2988. if (!MF.hasEHFunclets())
  2989. return;
  2990. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  2991. WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
  2992. MachineBasicBlock &MBB = MF.front();
  2993. auto MBBI = MBB.begin();
  2994. while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
  2995. ++MBBI;
  2996. // Create an UnwindHelp object.
  2997. // The UnwindHelp object is allocated at the start of the fixed object area
  2998. int64_t FixedObject =
  2999. getFixedObjectSize(MF, AFI, /*IsWin64*/ true, /*IsFunclet*/ false);
  3000. int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8,
  3001. /*SPOffset*/ -FixedObject,
  3002. /*IsImmutable=*/false);
  3003. EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
  3004. // We need to store -2 into the UnwindHelp object at the start of the
  3005. // function.
  3006. DebugLoc DL;
  3007. RS->enterBasicBlockEnd(MBB);
  3008. RS->backward(std::prev(MBBI));
  3009. Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
  3010. assert(DstReg && "There must be a free register after frame setup");
  3011. BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
  3012. BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
  3013. .addReg(DstReg, getKillRegState(true))
  3014. .addFrameIndex(UnwindHelpFI)
  3015. .addImm(0);
  3016. }
  3017. namespace {
  3018. struct TagStoreInstr {
  3019. MachineInstr *MI;
  3020. int64_t Offset, Size;
  3021. explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
  3022. : MI(MI), Offset(Offset), Size(Size) {}
  3023. };
  3024. class TagStoreEdit {
  3025. MachineFunction *MF;
  3026. MachineBasicBlock *MBB;
  3027. MachineRegisterInfo *MRI;
  3028. // Tag store instructions that are being replaced.
  3029. SmallVector<TagStoreInstr, 8> TagStores;
  3030. // Combined memref arguments of the above instructions.
  3031. SmallVector<MachineMemOperand *, 8> CombinedMemRefs;
  3032. // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
  3033. // FrameRegOffset + Size) with the address tag of SP.
  3034. Register FrameReg;
  3035. StackOffset FrameRegOffset;
  3036. int64_t Size;
  3037. // If not None, move FrameReg to (FrameReg + FrameRegUpdate) at the end.
  3038. std::optional<int64_t> FrameRegUpdate;
  3039. // MIFlags for any FrameReg updating instructions.
  3040. unsigned FrameRegUpdateFlags;
  3041. // Use zeroing instruction variants.
  3042. bool ZeroData;
  3043. DebugLoc DL;
  3044. void emitUnrolled(MachineBasicBlock::iterator InsertI);
  3045. void emitLoop(MachineBasicBlock::iterator InsertI);
  3046. public:
  3047. TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
  3048. : MBB(MBB), ZeroData(ZeroData) {
  3049. MF = MBB->getParent();
  3050. MRI = &MF->getRegInfo();
  3051. }
  3052. // Add an instruction to be replaced. Instructions must be added in the
  3053. // ascending order of Offset, and have to be adjacent.
  3054. void addInstruction(TagStoreInstr I) {
  3055. assert((TagStores.empty() ||
  3056. TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
  3057. "Non-adjacent tag store instructions.");
  3058. TagStores.push_back(I);
  3059. }
  3060. void clear() { TagStores.clear(); }
  3061. // Emit equivalent code at the given location, and erase the current set of
  3062. // instructions. May skip if the replacement is not profitable. May invalidate
  3063. // the input iterator and replace it with a valid one.
  3064. void emitCode(MachineBasicBlock::iterator &InsertI,
  3065. const AArch64FrameLowering *TFI, bool TryMergeSPUpdate);
  3066. };
  3067. void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
  3068. const AArch64InstrInfo *TII =
  3069. MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
  3070. const int64_t kMinOffset = -256 * 16;
  3071. const int64_t kMaxOffset = 255 * 16;
  3072. Register BaseReg = FrameReg;
  3073. int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed();
  3074. if (BaseRegOffsetBytes < kMinOffset ||
  3075. BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset) {
  3076. Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
  3077. emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
  3078. StackOffset::getFixed(BaseRegOffsetBytes), TII);
  3079. BaseReg = ScratchReg;
  3080. BaseRegOffsetBytes = 0;
  3081. }
  3082. MachineInstr *LastI = nullptr;
  3083. while (Size) {
  3084. int64_t InstrSize = (Size > 16) ? 32 : 16;
  3085. unsigned Opcode =
  3086. InstrSize == 16
  3087. ? (ZeroData ? AArch64::STZGOffset : AArch64::STGOffset)
  3088. : (ZeroData ? AArch64::STZ2GOffset : AArch64::ST2GOffset);
  3089. MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
  3090. .addReg(AArch64::SP)
  3091. .addReg(BaseReg)
  3092. .addImm(BaseRegOffsetBytes / 16)
  3093. .setMemRefs(CombinedMemRefs);
  3094. // A store to [BaseReg, #0] should go last for an opportunity to fold the
  3095. // final SP adjustment in the epilogue.
  3096. if (BaseRegOffsetBytes == 0)
  3097. LastI = I;
  3098. BaseRegOffsetBytes += InstrSize;
  3099. Size -= InstrSize;
  3100. }
  3101. if (LastI)
  3102. MBB->splice(InsertI, MBB, LastI);
  3103. }
  3104. void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
  3105. const AArch64InstrInfo *TII =
  3106. MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
  3107. Register BaseReg = FrameRegUpdate
  3108. ? FrameReg
  3109. : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
  3110. Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
  3111. emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
  3112. int64_t LoopSize = Size;
  3113. // If the loop size is not a multiple of 32, split off one 16-byte store at
  3114. // the end to fold BaseReg update into.
  3115. if (FrameRegUpdate && *FrameRegUpdate)
  3116. LoopSize -= LoopSize % 32;
  3117. MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
  3118. TII->get(ZeroData ? AArch64::STZGloop_wback
  3119. : AArch64::STGloop_wback))
  3120. .addDef(SizeReg)
  3121. .addDef(BaseReg)
  3122. .addImm(LoopSize)
  3123. .addReg(BaseReg)
  3124. .setMemRefs(CombinedMemRefs);
  3125. if (FrameRegUpdate)
  3126. LoopI->setFlags(FrameRegUpdateFlags);
  3127. int64_t ExtraBaseRegUpdate =
  3128. FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0;
  3129. if (LoopSize < Size) {
  3130. assert(FrameRegUpdate);
  3131. assert(Size - LoopSize == 16);
  3132. // Tag 16 more bytes at BaseReg and update BaseReg.
  3133. BuildMI(*MBB, InsertI, DL,
  3134. TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
  3135. .addDef(BaseReg)
  3136. .addReg(BaseReg)
  3137. .addReg(BaseReg)
  3138. .addImm(1 + ExtraBaseRegUpdate / 16)
  3139. .setMemRefs(CombinedMemRefs)
  3140. .setMIFlags(FrameRegUpdateFlags);
  3141. } else if (ExtraBaseRegUpdate) {
  3142. // Update BaseReg.
  3143. BuildMI(
  3144. *MBB, InsertI, DL,
  3145. TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
  3146. .addDef(BaseReg)
  3147. .addReg(BaseReg)
  3148. .addImm(std::abs(ExtraBaseRegUpdate))
  3149. .addImm(0)
  3150. .setMIFlags(FrameRegUpdateFlags);
  3151. }
  3152. }
  3153. // Check if *II is a register update that can be merged into STGloop that ends
  3154. // at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
  3155. // end of the loop.
  3156. bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
  3157. int64_t Size, int64_t *TotalOffset) {
  3158. MachineInstr &MI = *II;
  3159. if ((MI.getOpcode() == AArch64::ADDXri ||
  3160. MI.getOpcode() == AArch64::SUBXri) &&
  3161. MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
  3162. unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
  3163. int64_t Offset = MI.getOperand(2).getImm() << Shift;
  3164. if (MI.getOpcode() == AArch64::SUBXri)
  3165. Offset = -Offset;
  3166. int64_t AbsPostOffset = std::abs(Offset - Size);
  3167. const int64_t kMaxOffset =
  3168. 0xFFF; // Max encoding for unshifted ADDXri / SUBXri
  3169. if (AbsPostOffset <= kMaxOffset && AbsPostOffset % 16 == 0) {
  3170. *TotalOffset = Offset;
  3171. return true;
  3172. }
  3173. }
  3174. return false;
  3175. }
  3176. void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
  3177. SmallVectorImpl<MachineMemOperand *> &MemRefs) {
  3178. MemRefs.clear();
  3179. for (auto &TS : TSE) {
  3180. MachineInstr *MI = TS.MI;
  3181. // An instruction without memory operands may access anything. Be
  3182. // conservative and return an empty list.
  3183. if (MI->memoperands_empty()) {
  3184. MemRefs.clear();
  3185. return;
  3186. }
  3187. MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
  3188. }
  3189. }
  3190. void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
  3191. const AArch64FrameLowering *TFI,
  3192. bool TryMergeSPUpdate) {
  3193. if (TagStores.empty())
  3194. return;
  3195. TagStoreInstr &FirstTagStore = TagStores[0];
  3196. TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
  3197. Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
  3198. DL = TagStores[0].MI->getDebugLoc();
  3199. Register Reg;
  3200. FrameRegOffset = TFI->resolveFrameOffsetReference(
  3201. *MF, FirstTagStore.Offset, false /*isFixed*/, false /*isSVE*/, Reg,
  3202. /*PreferFP=*/false, /*ForSimm=*/true);
  3203. FrameReg = Reg;
  3204. FrameRegUpdate = std::nullopt;
  3205. mergeMemRefs(TagStores, CombinedMemRefs);
  3206. LLVM_DEBUG(dbgs() << "Replacing adjacent STG instructions:\n";
  3207. for (const auto &Instr
  3208. : TagStores) { dbgs() << " " << *Instr.MI; });
  3209. // Size threshold where a loop becomes shorter than a linear sequence of
  3210. // tagging instructions.
  3211. const int kSetTagLoopThreshold = 176;
  3212. if (Size < kSetTagLoopThreshold) {
  3213. if (TagStores.size() < 2)
  3214. return;
  3215. emitUnrolled(InsertI);
  3216. } else {
  3217. MachineInstr *UpdateInstr = nullptr;
  3218. int64_t TotalOffset = 0;
  3219. if (TryMergeSPUpdate) {
  3220. // See if we can merge base register update into the STGloop.
  3221. // This is done in AArch64LoadStoreOptimizer for "normal" stores,
  3222. // but STGloop is way too unusual for that, and also it only
  3223. // realistically happens in function epilogue. Also, STGloop is expanded
  3224. // before that pass.
  3225. if (InsertI != MBB->end() &&
  3226. canMergeRegUpdate(InsertI, FrameReg, FrameRegOffset.getFixed() + Size,
  3227. &TotalOffset)) {
  3228. UpdateInstr = &*InsertI++;
  3229. LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n "
  3230. << *UpdateInstr);
  3231. }
  3232. }
  3233. if (!UpdateInstr && TagStores.size() < 2)
  3234. return;
  3235. if (UpdateInstr) {
  3236. FrameRegUpdate = TotalOffset;
  3237. FrameRegUpdateFlags = UpdateInstr->getFlags();
  3238. }
  3239. emitLoop(InsertI);
  3240. if (UpdateInstr)
  3241. UpdateInstr->eraseFromParent();
  3242. }
  3243. for (auto &TS : TagStores)
  3244. TS.MI->eraseFromParent();
  3245. }
  3246. bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
  3247. int64_t &Size, bool &ZeroData) {
  3248. MachineFunction &MF = *MI.getParent()->getParent();
  3249. const MachineFrameInfo &MFI = MF.getFrameInfo();
  3250. unsigned Opcode = MI.getOpcode();
  3251. ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGOffset ||
  3252. Opcode == AArch64::STZ2GOffset);
  3253. if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
  3254. if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
  3255. return false;
  3256. if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
  3257. return false;
  3258. Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
  3259. Size = MI.getOperand(2).getImm();
  3260. return true;
  3261. }
  3262. if (Opcode == AArch64::STGOffset || Opcode == AArch64::STZGOffset)
  3263. Size = 16;
  3264. else if (Opcode == AArch64::ST2GOffset || Opcode == AArch64::STZ2GOffset)
  3265. Size = 32;
  3266. else
  3267. return false;
  3268. if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
  3269. return false;
  3270. Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
  3271. 16 * MI.getOperand(2).getImm();
  3272. return true;
  3273. }
  3274. // Detect a run of memory tagging instructions for adjacent stack frame slots,
  3275. // and replace them with a shorter instruction sequence:
  3276. // * replace STG + STG with ST2G
  3277. // * replace STGloop + STGloop with STGloop
  3278. // This code needs to run when stack slot offsets are already known, but before
  3279. // FrameIndex operands in STG instructions are eliminated.
  3280. MachineBasicBlock::iterator tryMergeAdjacentSTG(MachineBasicBlock::iterator II,
  3281. const AArch64FrameLowering *TFI,
  3282. RegScavenger *RS) {
  3283. bool FirstZeroData;
  3284. int64_t Size, Offset;
  3285. MachineInstr &MI = *II;
  3286. MachineBasicBlock *MBB = MI.getParent();
  3287. MachineBasicBlock::iterator NextI = ++II;
  3288. if (&MI == &MBB->instr_back())
  3289. return II;
  3290. if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
  3291. return II;
  3292. SmallVector<TagStoreInstr, 4> Instrs;
  3293. Instrs.emplace_back(&MI, Offset, Size);
  3294. constexpr int kScanLimit = 10;
  3295. int Count = 0;
  3296. for (MachineBasicBlock::iterator E = MBB->end();
  3297. NextI != E && Count < kScanLimit; ++NextI) {
  3298. MachineInstr &MI = *NextI;
  3299. bool ZeroData;
  3300. int64_t Size, Offset;
  3301. // Collect instructions that update memory tags with a FrameIndex operand
  3302. // and (when applicable) constant size, and whose output registers are dead
  3303. // (the latter is almost always the case in practice). Since these
  3304. // instructions effectively have no inputs or outputs, we are free to skip
  3305. // any non-aliasing instructions in between without tracking used registers.
  3306. if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
  3307. if (ZeroData != FirstZeroData)
  3308. break;
  3309. Instrs.emplace_back(&MI, Offset, Size);
  3310. continue;
  3311. }
  3312. // Only count non-transient, non-tagging instructions toward the scan
  3313. // limit.
  3314. if (!MI.isTransient())
  3315. ++Count;
  3316. // Just in case, stop before the epilogue code starts.
  3317. if (MI.getFlag(MachineInstr::FrameSetup) ||
  3318. MI.getFlag(MachineInstr::FrameDestroy))
  3319. break;
  3320. // Reject anything that may alias the collected instructions.
  3321. if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects())
  3322. break;
  3323. }
  3324. // New code will be inserted after the last tagging instruction we've found.
  3325. MachineBasicBlock::iterator InsertI = Instrs.back().MI;
  3326. InsertI++;
  3327. llvm::stable_sort(Instrs,
  3328. [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
  3329. return Left.Offset < Right.Offset;
  3330. });
  3331. // Make sure that we don't have any overlapping stores.
  3332. int64_t CurOffset = Instrs[0].Offset;
  3333. for (auto &Instr : Instrs) {
  3334. if (CurOffset > Instr.Offset)
  3335. return NextI;
  3336. CurOffset = Instr.Offset + Instr.Size;
  3337. }
  3338. // Find contiguous runs of tagged memory and emit shorter instruction
  3339. // sequencies for them when possible.
  3340. TagStoreEdit TSE(MBB, FirstZeroData);
  3341. std::optional<int64_t> EndOffset;
  3342. for (auto &Instr : Instrs) {
  3343. if (EndOffset && *EndOffset != Instr.Offset) {
  3344. // Found a gap.
  3345. TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */ false);
  3346. TSE.clear();
  3347. }
  3348. TSE.addInstruction(Instr);
  3349. EndOffset = Instr.Offset + Instr.Size;
  3350. }
  3351. const MachineFunction *MF = MBB->getParent();
  3352. // Multiple FP/SP updates in a loop cannot be described by CFI instructions.
  3353. TSE.emitCode(
  3354. InsertI, TFI, /*TryMergeSPUpdate = */
  3355. !MF->getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(*MF));
  3356. return InsertI;
  3357. }
  3358. } // namespace
  3359. void AArch64FrameLowering::processFunctionBeforeFrameIndicesReplaced(
  3360. MachineFunction &MF, RegScavenger *RS = nullptr) const {
  3361. if (StackTaggingMergeSetTag)
  3362. for (auto &BB : MF)
  3363. for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();)
  3364. II = tryMergeAdjacentSTG(II, this, RS);
  3365. }
  3366. /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
  3367. /// before the update. This is easily retrieved as it is exactly the offset
  3368. /// that is set in processFunctionBeforeFrameFinalized.
  3369. StackOffset AArch64FrameLowering::getFrameIndexReferencePreferSP(
  3370. const MachineFunction &MF, int FI, Register &FrameReg,
  3371. bool IgnoreSPUpdates) const {
  3372. const MachineFrameInfo &MFI = MF.getFrameInfo();
  3373. if (IgnoreSPUpdates) {
  3374. LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
  3375. << MFI.getObjectOffset(FI) << "\n");
  3376. FrameReg = AArch64::SP;
  3377. return StackOffset::getFixed(MFI.getObjectOffset(FI));
  3378. }
  3379. // Go to common code if we cannot provide sp + offset.
  3380. if (MFI.hasVarSizedObjects() ||
  3381. MF.getInfo<AArch64FunctionInfo>()->getStackSizeSVE() ||
  3382. MF.getSubtarget().getRegisterInfo()->hasStackRealignment(MF))
  3383. return getFrameIndexReference(MF, FI, FrameReg);
  3384. FrameReg = AArch64::SP;
  3385. return getStackOffset(MF, MFI.getObjectOffset(FI));
  3386. }
  3387. /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
  3388. /// the parent's frame pointer
  3389. unsigned AArch64FrameLowering::getWinEHParentFrameOffset(
  3390. const MachineFunction &MF) const {
  3391. return 0;
  3392. }
  3393. /// Funclets only need to account for space for the callee saved registers,
  3394. /// as the locals are accounted for in the parent's stack frame.
  3395. unsigned AArch64FrameLowering::getWinEHFuncletFrameSize(
  3396. const MachineFunction &MF) const {
  3397. // This is the size of the pushed CSRs.
  3398. unsigned CSSize =
  3399. MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
  3400. // This is the amount of stack a funclet needs to allocate.
  3401. return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
  3402. getStackAlign());
  3403. }
  3404. namespace {
  3405. struct FrameObject {
  3406. bool IsValid = false;
  3407. // Index of the object in MFI.
  3408. int ObjectIndex = 0;
  3409. // Group ID this object belongs to.
  3410. int GroupIndex = -1;
  3411. // This object should be placed first (closest to SP).
  3412. bool ObjectFirst = false;
  3413. // This object's group (which always contains the object with
  3414. // ObjectFirst==true) should be placed first.
  3415. bool GroupFirst = false;
  3416. };
  3417. class GroupBuilder {
  3418. SmallVector<int, 8> CurrentMembers;
  3419. int NextGroupIndex = 0;
  3420. std::vector<FrameObject> &Objects;
  3421. public:
  3422. GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {}
  3423. void AddMember(int Index) { CurrentMembers.push_back(Index); }
  3424. void EndCurrentGroup() {
  3425. if (CurrentMembers.size() > 1) {
  3426. // Create a new group with the current member list. This might remove them
  3427. // from their pre-existing groups. That's OK, dealing with overlapping
  3428. // groups is too hard and unlikely to make a difference.
  3429. LLVM_DEBUG(dbgs() << "group:");
  3430. for (int Index : CurrentMembers) {
  3431. Objects[Index].GroupIndex = NextGroupIndex;
  3432. LLVM_DEBUG(dbgs() << " " << Index);
  3433. }
  3434. LLVM_DEBUG(dbgs() << "\n");
  3435. NextGroupIndex++;
  3436. }
  3437. CurrentMembers.clear();
  3438. }
  3439. };
  3440. bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) {
  3441. // Objects at a lower index are closer to FP; objects at a higher index are
  3442. // closer to SP.
  3443. //
  3444. // For consistency in our comparison, all invalid objects are placed
  3445. // at the end. This also allows us to stop walking when we hit the
  3446. // first invalid item after it's all sorted.
  3447. //
  3448. // The "first" object goes first (closest to SP), followed by the members of
  3449. // the "first" group.
  3450. //
  3451. // The rest are sorted by the group index to keep the groups together.
  3452. // Higher numbered groups are more likely to be around longer (i.e. untagged
  3453. // in the function epilogue and not at some earlier point). Place them closer
  3454. // to SP.
  3455. //
  3456. // If all else equal, sort by the object index to keep the objects in the
  3457. // original order.
  3458. return std::make_tuple(!A.IsValid, A.ObjectFirst, A.GroupFirst, A.GroupIndex,
  3459. A.ObjectIndex) <
  3460. std::make_tuple(!B.IsValid, B.ObjectFirst, B.GroupFirst, B.GroupIndex,
  3461. B.ObjectIndex);
  3462. }
  3463. } // namespace
  3464. void AArch64FrameLowering::orderFrameObjects(
  3465. const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
  3466. if (!OrderFrameObjects || ObjectsToAllocate.empty())
  3467. return;
  3468. const MachineFrameInfo &MFI = MF.getFrameInfo();
  3469. std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd());
  3470. for (auto &Obj : ObjectsToAllocate) {
  3471. FrameObjects[Obj].IsValid = true;
  3472. FrameObjects[Obj].ObjectIndex = Obj;
  3473. }
  3474. // Identify stack slots that are tagged at the same time.
  3475. GroupBuilder GB(FrameObjects);
  3476. for (auto &MBB : MF) {
  3477. for (auto &MI : MBB) {
  3478. if (MI.isDebugInstr())
  3479. continue;
  3480. int OpIndex;
  3481. switch (MI.getOpcode()) {
  3482. case AArch64::STGloop:
  3483. case AArch64::STZGloop:
  3484. OpIndex = 3;
  3485. break;
  3486. case AArch64::STGOffset:
  3487. case AArch64::STZGOffset:
  3488. case AArch64::ST2GOffset:
  3489. case AArch64::STZ2GOffset:
  3490. OpIndex = 1;
  3491. break;
  3492. default:
  3493. OpIndex = -1;
  3494. }
  3495. int TaggedFI = -1;
  3496. if (OpIndex >= 0) {
  3497. const MachineOperand &MO = MI.getOperand(OpIndex);
  3498. if (MO.isFI()) {
  3499. int FI = MO.getIndex();
  3500. if (FI >= 0 && FI < MFI.getObjectIndexEnd() &&
  3501. FrameObjects[FI].IsValid)
  3502. TaggedFI = FI;
  3503. }
  3504. }
  3505. // If this is a stack tagging instruction for a slot that is not part of a
  3506. // group yet, either start a new group or add it to the current one.
  3507. if (TaggedFI >= 0)
  3508. GB.AddMember(TaggedFI);
  3509. else
  3510. GB.EndCurrentGroup();
  3511. }
  3512. // Groups should never span multiple basic blocks.
  3513. GB.EndCurrentGroup();
  3514. }
  3515. // If the function's tagged base pointer is pinned to a stack slot, we want to
  3516. // put that slot first when possible. This will likely place it at SP + 0,
  3517. // and save one instruction when generating the base pointer because IRG does
  3518. // not allow an immediate offset.
  3519. const AArch64FunctionInfo &AFI = *MF.getInfo<AArch64FunctionInfo>();
  3520. std::optional<int> TBPI = AFI.getTaggedBasePointerIndex();
  3521. if (TBPI) {
  3522. FrameObjects[*TBPI].ObjectFirst = true;
  3523. FrameObjects[*TBPI].GroupFirst = true;
  3524. int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex;
  3525. if (FirstGroupIndex >= 0)
  3526. for (FrameObject &Object : FrameObjects)
  3527. if (Object.GroupIndex == FirstGroupIndex)
  3528. Object.GroupFirst = true;
  3529. }
  3530. llvm::stable_sort(FrameObjects, FrameObjectCompare);
  3531. int i = 0;
  3532. for (auto &Obj : FrameObjects) {
  3533. // All invalid items are sorted at the end, so it's safe to stop.
  3534. if (!Obj.IsValid)
  3535. break;
  3536. ObjectsToAllocate[i++] = Obj.ObjectIndex;
  3537. }
  3538. LLVM_DEBUG(dbgs() << "Final frame order:\n"; for (auto &Obj
  3539. : FrameObjects) {
  3540. if (!Obj.IsValid)
  3541. break;
  3542. dbgs() << " " << Obj.ObjectIndex << ": group " << Obj.GroupIndex;
  3543. if (Obj.ObjectFirst)
  3544. dbgs() << ", first";
  3545. if (Obj.GroupFirst)
  3546. dbgs() << ", group-first";
  3547. dbgs() << "\n";
  3548. });
  3549. }